clang  17.0.0git
SemaDecl.cpp
Go to the documentation of this file.
1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/Randstruct.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
36 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
37 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
39 #include "clang/Sema/DeclSpec.h"
42 #include "clang/Sema/Lookup.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
47 #include "clang/Sema/Template.h"
48 #include "llvm/ADT/SmallString.h"
49 #include "llvm/TargetParser/Triple.h"
50 #include <algorithm>
51 #include <cstring>
52 #include <functional>
53 #include <optional>
54 #include <unordered_map>
55 
56 using namespace clang;
57 using namespace sema;
58 
60  if (OwnedType) {
61  Decl *Group[2] = { OwnedType, Ptr };
62  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
63  }
64 
65  return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
66 }
67 
68 namespace {
69 
70 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
71  public:
72  TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
73  bool AllowTemplates = false,
74  bool AllowNonTemplates = true)
75  : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
76  AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
77  WantExpressionKeywords = false;
78  WantCXXNamedCasts = false;
79  WantRemainingKeywords = false;
80  }
81 
82  bool ValidateCandidate(const TypoCorrection &candidate) override {
83  if (NamedDecl *ND = candidate.getCorrectionDecl()) {
84  if (!AllowInvalidDecl && ND->isInvalidDecl())
85  return false;
86 
87  if (getAsTypeTemplateDecl(ND))
88  return AllowTemplates;
89 
90  bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
91  if (!IsType)
92  return false;
93 
94  if (AllowNonTemplates)
95  return true;
96 
97  // An injected-class-name of a class template (specialization) is valid
98  // as a template or as a non-template.
99  if (AllowTemplates) {
100  auto *RD = dyn_cast<CXXRecordDecl>(ND);
101  if (!RD || !RD->isInjectedClassName())
102  return false;
103  RD = cast<CXXRecordDecl>(RD->getDeclContext());
104  return RD->getDescribedClassTemplate() ||
105  isa<ClassTemplateSpecializationDecl>(RD);
106  }
107 
108  return false;
109  }
110 
111  return !WantClassName && candidate.isKeyword();
112  }
113 
114  std::unique_ptr<CorrectionCandidateCallback> clone() override {
115  return std::make_unique<TypeNameValidatorCCC>(*this);
116  }
117 
118  private:
119  bool AllowInvalidDecl;
120  bool WantClassName;
121  bool AllowTemplates;
122  bool AllowNonTemplates;
123 };
124 
125 } // end anonymous namespace
126 
127 /// Determine whether the token kind starts a simple-type-specifier.
129  switch (Kind) {
130  // FIXME: Take into account the current language when deciding whether a
131  // token kind is a valid type specifier
132  case tok::kw_short:
133  case tok::kw_long:
134  case tok::kw___int64:
135  case tok::kw___int128:
136  case tok::kw_signed:
137  case tok::kw_unsigned:
138  case tok::kw_void:
139  case tok::kw_char:
140  case tok::kw_int:
141  case tok::kw_half:
142  case tok::kw_float:
143  case tok::kw_double:
144  case tok::kw___bf16:
145  case tok::kw__Float16:
146  case tok::kw___float128:
147  case tok::kw___ibm128:
148  case tok::kw_wchar_t:
149  case tok::kw_bool:
150 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
151 #include "clang/Basic/TransformTypeTraits.def"
152  case tok::kw___auto_type:
153  return true;
154 
155  case tok::annot_typename:
156  case tok::kw_char16_t:
157  case tok::kw_char32_t:
158  case tok::kw_typeof:
159  case tok::annot_decltype:
160  case tok::kw_decltype:
161  return getLangOpts().CPlusPlus;
162 
163  case tok::kw_char8_t:
164  return getLangOpts().Char8;
165 
166  default:
167  break;
168  }
169 
170  return false;
171 }
172 
173 namespace {
174 enum class UnqualifiedTypeNameLookupResult {
175  NotFound,
176  FoundNonType,
177  FoundType
178 };
179 } // end anonymous namespace
180 
181 /// Tries to perform unqualified lookup of the type decls in bases for
182 /// dependent class.
183 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
184 /// type decl, \a FoundType if only type decls are found.
185 static UnqualifiedTypeNameLookupResult
187  SourceLocation NameLoc,
188  const CXXRecordDecl *RD) {
189  if (!RD->hasDefinition())
190  return UnqualifiedTypeNameLookupResult::NotFound;
191  // Look for type decls in base classes.
192  UnqualifiedTypeNameLookupResult FoundTypeDecl =
193  UnqualifiedTypeNameLookupResult::NotFound;
194  for (const auto &Base : RD->bases()) {
195  const CXXRecordDecl *BaseRD = nullptr;
196  if (auto *BaseTT = Base.getType()->getAs<TagType>())
197  BaseRD = BaseTT->getAsCXXRecordDecl();
198  else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
199  // Look for type decls in dependent base classes that have known primary
200  // templates.
201  if (!TST || !TST->isDependentType())
202  continue;
203  auto *TD = TST->getTemplateName().getAsTemplateDecl();
204  if (!TD)
205  continue;
206  if (auto *BasePrimaryTemplate =
207  dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
208  if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
209  BaseRD = BasePrimaryTemplate;
210  else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
212  CTD->findPartialSpecialization(Base.getType()))
213  if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
214  BaseRD = PS;
215  }
216  }
217  }
218  if (BaseRD) {
219  for (NamedDecl *ND : BaseRD->lookup(&II)) {
220  if (!isa<TypeDecl>(ND))
221  return UnqualifiedTypeNameLookupResult::FoundNonType;
222  FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
223  }
224  if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
225  switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
226  case UnqualifiedTypeNameLookupResult::FoundNonType:
227  return UnqualifiedTypeNameLookupResult::FoundNonType;
228  case UnqualifiedTypeNameLookupResult::FoundType:
229  FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
230  break;
231  case UnqualifiedTypeNameLookupResult::NotFound:
232  break;
233  }
234  }
235  }
236  }
237 
238  return FoundTypeDecl;
239 }
240 
242  const IdentifierInfo &II,
243  SourceLocation NameLoc) {
244  // Lookup in the parent class template context, if any.
245  const CXXRecordDecl *RD = nullptr;
246  UnqualifiedTypeNameLookupResult FoundTypeDecl =
247  UnqualifiedTypeNameLookupResult::NotFound;
248  for (DeclContext *DC = S.CurContext;
249  DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
250  DC = DC->getParent()) {
251  // Look for type decls in dependent base classes that have known primary
252  // templates.
253  RD = dyn_cast<CXXRecordDecl>(DC);
254  if (RD && RD->getDescribedClassTemplate())
255  FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
256  }
257  if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
258  return nullptr;
259 
260  // We found some types in dependent base classes. Recover as if the user
261  // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
262  // lookup during template instantiation.
263  S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
264 
265  ASTContext &Context = S.Context;
266  auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
267  cast<Type>(Context.getRecordType(RD)));
268  QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
269 
270  CXXScopeSpec SS;
271  SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
272 
273  TypeLocBuilder Builder;
274  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
275  DepTL.setNameLoc(NameLoc);
277  DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
278  return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
279 }
280 
281 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
283  SourceLocation NameLoc,
284  bool WantNontrivialTypeSourceInfo = true) {
285  switch (T->getTypeClass()) {
286  case Type::DeducedTemplateSpecialization:
287  case Type::Enum:
288  case Type::InjectedClassName:
289  case Type::Record:
290  case Type::Typedef:
291  case Type::UnresolvedUsing:
292  case Type::Using:
293  break;
294  // These can never be qualified so an ElaboratedType node
295  // would carry no additional meaning.
296  case Type::ObjCInterface:
297  case Type::ObjCTypeParam:
298  case Type::TemplateTypeParm:
299  return ParsedType::make(T);
300  default:
301  llvm_unreachable("Unexpected Type Class");
302  }
303 
304  if (!SS || SS->isEmpty())
305  return ParsedType::make(
306  S.Context.getElaboratedType(ETK_None, nullptr, T, nullptr));
307 
308  QualType ElTy = S.getElaboratedType(ETK_None, *SS, T);
309  if (!WantNontrivialTypeSourceInfo)
310  return ParsedType::make(ElTy);
311 
312  TypeLocBuilder Builder;
313  Builder.pushTypeSpec(T).setNameLoc(NameLoc);
314  ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
317  return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
318 }
319 
320 /// If the identifier refers to a type name within this scope,
321 /// return the declaration of that type.
322 ///
323 /// This routine performs ordinary name lookup of the identifier II
324 /// within the given scope, with optional C++ scope specifier SS, to
325 /// determine whether the name refers to a type. If so, returns an
326 /// opaque pointer (actually a QualType) corresponding to that
327 /// type. Otherwise, returns NULL.
329  Scope *S, CXXScopeSpec *SS, bool isClassName,
330  bool HasTrailingDot, ParsedType ObjectTypePtr,
331  bool IsCtorOrDtorName,
332  bool WantNontrivialTypeSourceInfo,
333  bool IsClassTemplateDeductionContext,
334  ImplicitTypenameContext AllowImplicitTypename,
335  IdentifierInfo **CorrectedII) {
336  // FIXME: Consider allowing this outside C++1z mode as an extension.
337  bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
338  getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
339  !isClassName && !HasTrailingDot;
340 
341  // Determine where we will perform name lookup.
342  DeclContext *LookupCtx = nullptr;
343  if (ObjectTypePtr) {
344  QualType ObjectType = ObjectTypePtr.get();
345  if (ObjectType->isRecordType())
346  LookupCtx = computeDeclContext(ObjectType);
347  } else if (SS && SS->isNotEmpty()) {
348  LookupCtx = computeDeclContext(*SS, false);
349 
350  if (!LookupCtx) {
351  if (isDependentScopeSpecifier(*SS)) {
352  // C++ [temp.res]p3:
353  // A qualified-id that refers to a type and in which the
354  // nested-name-specifier depends on a template-parameter (14.6.2)
355  // shall be prefixed by the keyword typename to indicate that the
356  // qualified-id denotes a type, forming an
357  // elaborated-type-specifier (7.1.5.3).
358  //
359  // We therefore do not perform any name lookup if the result would
360  // refer to a member of an unknown specialization.
361  // In C++2a, in several contexts a 'typename' is not required. Also
362  // allow this as an extension.
363  if (AllowImplicitTypename == ImplicitTypenameContext::No &&
364  !isClassName && !IsCtorOrDtorName)
365  return nullptr;
366  bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
367  if (IsImplicitTypename) {
368  SourceLocation QualifiedLoc = SS->getRange().getBegin();
369  if (getLangOpts().CPlusPlus20)
370  Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
371  else
372  Diag(QualifiedLoc, diag::ext_implicit_typename)
373  << SS->getScopeRep() << II.getName()
374  << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
375  }
376 
377  // We know from the grammar that this name refers to a type,
378  // so build a dependent node to describe the type.
379  if (WantNontrivialTypeSourceInfo)
380  return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
381  (ImplicitTypenameContext)IsImplicitTypename)
382  .get();
383 
384  NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
385  QualType T =
386  CheckTypenameType(IsImplicitTypename ? ETK_Typename : ETK_None,
387  SourceLocation(), QualifierLoc, II, NameLoc);
388  return ParsedType::make(T);
389  }
390 
391  return nullptr;
392  }
393 
394  if (!LookupCtx->isDependentContext() &&
395  RequireCompleteDeclContext(*SS, LookupCtx))
396  return nullptr;
397  }
398 
399  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
400  // lookup for class-names.
401  LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
402  LookupOrdinaryName;
403  LookupResult Result(*this, &II, NameLoc, Kind);
404  if (LookupCtx) {
405  // Perform "qualified" name lookup into the declaration context we
406  // computed, which is either the type of the base of a member access
407  // expression or the declaration context associated with a prior
408  // nested-name-specifier.
409  LookupQualifiedName(Result, LookupCtx);
410 
411  if (ObjectTypePtr && Result.empty()) {
412  // C++ [basic.lookup.classref]p3:
413  // If the unqualified-id is ~type-name, the type-name is looked up
414  // in the context of the entire postfix-expression. If the type T of
415  // the object expression is of a class type C, the type-name is also
416  // looked up in the scope of class C. At least one of the lookups shall
417  // find a name that refers to (possibly cv-qualified) T.
418  LookupName(Result, S);
419  }
420  } else {
421  // Perform unqualified name lookup.
422  LookupName(Result, S);
423 
424  // For unqualified lookup in a class template in MSVC mode, look into
425  // dependent base classes where the primary class template is known.
426  if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
427  if (ParsedType TypeInBase =
428  recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
429  return TypeInBase;
430  }
431  }
432 
433  NamedDecl *IIDecl = nullptr;
434  UsingShadowDecl *FoundUsingShadow = nullptr;
435  switch (Result.getResultKind()) {
438  if (CorrectedII) {
439  TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
440  AllowDeducedTemplate);
441  TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
442  S, SS, CCC, CTK_ErrorRecovery);
443  IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
444  TemplateTy Template;
445  bool MemberOfUnknownSpecialization;
447  TemplateName.setIdentifier(NewII, NameLoc);
448  NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
449  CXXScopeSpec NewSS, *NewSSPtr = SS;
450  if (SS && NNS) {
451  NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
452  NewSSPtr = &NewSS;
453  }
454  if (Correction && (NNS || NewII != &II) &&
455  // Ignore a correction to a template type as the to-be-corrected
456  // identifier is not a template (typo correction for template names
457  // is handled elsewhere).
458  !(getLangOpts().CPlusPlus && NewSSPtr &&
459  isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
460  Template, MemberOfUnknownSpecialization))) {
461  ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
462  isClassName, HasTrailingDot, ObjectTypePtr,
463  IsCtorOrDtorName,
464  WantNontrivialTypeSourceInfo,
465  IsClassTemplateDeductionContext);
466  if (Ty) {
467  diagnoseTypo(Correction,
468  PDiag(diag::err_unknown_type_or_class_name_suggest)
469  << Result.getLookupName() << isClassName);
470  if (SS && NNS)
471  SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
472  *CorrectedII = NewII;
473  return Ty;
474  }
475  }
476  }
477  // If typo correction failed or was not performed, fall through
478  [[fallthrough]];
481  Result.suppressDiagnostics();
482  return nullptr;
483 
485  // Recover from type-hiding ambiguities by hiding the type. We'll
486  // do the lookup again when looking for an object, and we can
487  // diagnose the error then. If we don't do this, then the error
488  // about hiding the type will be immediately followed by an error
489  // that only makes sense if the identifier was treated like a type.
490  if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
491  Result.suppressDiagnostics();
492  return nullptr;
493  }
494 
495  // Look to see if we have a type anywhere in the list of results.
496  for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
497  Res != ResEnd; ++Res) {
498  NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
499  if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
500  RealRes) ||
501  (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
502  if (!IIDecl ||
503  // Make the selection of the recovery decl deterministic.
504  RealRes->getLocation() < IIDecl->getLocation()) {
505  IIDecl = RealRes;
506  FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
507  }
508  }
509  }
510 
511  if (!IIDecl) {
512  // None of the entities we found is a type, so there is no way
513  // to even assume that the result is a type. In this case, don't
514  // complain about the ambiguity. The parser will either try to
515  // perform this lookup again (e.g., as an object name), which
516  // will produce the ambiguity, or will complain that it expected
517  // a type name.
518  Result.suppressDiagnostics();
519  return nullptr;
520  }
521 
522  // We found a type within the ambiguous lookup; diagnose the
523  // ambiguity and then return that type. This might be the right
524  // answer, or it might not be, but it suppresses any attempt to
525  // perform the name lookup again.
526  break;
527 
528  case LookupResult::Found:
529  IIDecl = Result.getFoundDecl();
530  FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
531  break;
532  }
533 
534  assert(IIDecl && "Didn't find decl");
535 
536  QualType T;
537  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
538  // C++ [class.qual]p2: A lookup that would find the injected-class-name
539  // instead names the constructors of the class, except when naming a class.
540  // This is ill-formed when we're not actually forming a ctor or dtor name.
541  auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
542  auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
543  if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
544  FoundRD->isInjectedClassName() &&
545  declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
546  Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
547  << &II << /*Type*/1;
548 
549  DiagnoseUseOfDecl(IIDecl, NameLoc);
550 
551  T = Context.getTypeDeclType(TD);
552  MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
553  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
554  (void)DiagnoseUseOfDecl(IDecl, NameLoc);
555  if (!HasTrailingDot)
556  T = Context.getObjCInterfaceType(IDecl);
557  FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
558  } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
559  (void)DiagnoseUseOfDecl(UD, NameLoc);
560  // Recover with 'int'
561  return ParsedType::make(Context.IntTy);
562  } else if (AllowDeducedTemplate) {
563  if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
564  assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
565  TemplateName Template =
566  FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
567  T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
568  false);
569  // Don't wrap in a further UsingType.
570  FoundUsingShadow = nullptr;
571  }
572  }
573 
574  if (T.isNull()) {
575  // If it's not plausibly a type, suppress diagnostics.
576  Result.suppressDiagnostics();
577  return nullptr;
578  }
579 
580  if (FoundUsingShadow)
581  T = Context.getUsingType(FoundUsingShadow, T);
582 
583  return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
584 }
585 
586 // Builds a fake NNS for the given decl context.
587 static NestedNameSpecifier *
589  for (;; DC = DC->getLookupParent()) {
590  DC = DC->getPrimaryContext();
591  auto *ND = dyn_cast<NamespaceDecl>(DC);
592  if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
593  return NestedNameSpecifier::Create(Context, nullptr, ND);
594  else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
595  return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
596  RD->getTypeForDecl());
597  else if (isa<TranslationUnitDecl>(DC))
598  return NestedNameSpecifier::GlobalSpecifier(Context);
599  }
600  llvm_unreachable("something isn't in TU scope?");
601 }
602 
603 /// Find the parent class with dependent bases of the innermost enclosing method
604 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
605 /// up allowing unqualified dependent type names at class-level, which MSVC
606 /// correctly rejects.
607 static const CXXRecordDecl *
609  for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
610  DC = DC->getPrimaryContext();
611  if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
612  if (MD->getParent()->hasAnyDependentBases())
613  return MD->getParent();
614  }
615  return nullptr;
616 }
617 
619  SourceLocation NameLoc,
620  bool IsTemplateTypeArg) {
621  assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
622 
623  NestedNameSpecifier *NNS = nullptr;
624  if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
625  // If we weren't able to parse a default template argument, delay lookup
626  // until instantiation time by making a non-dependent DependentTypeName. We
627  // pretend we saw a NestedNameSpecifier referring to the current scope, and
628  // lookup is retried.
629  // FIXME: This hurts our diagnostic quality, since we get errors like "no
630  // type named 'Foo' in 'current_namespace'" when the user didn't write any
631  // name specifiers.
632  NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
633  Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
634  } else if (const CXXRecordDecl *RD =
636  // Build a DependentNameType that will perform lookup into RD at
637  // instantiation time.
638  NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
639  RD->getTypeForDecl());
640 
641  // Diagnose that this identifier was undeclared, and retry the lookup during
642  // template instantiation.
643  Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
644  << RD;
645  } else {
646  // This is not a situation that we should recover from.
647  return ParsedType();
648  }
649 
650  QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
651 
652  // Build type location information. We synthesized the qualifier, so we have
653  // to build a fake NestedNameSpecifierLoc.
654  NestedNameSpecifierLocBuilder NNSLocBuilder;
655  NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
656  NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
657 
658  TypeLocBuilder Builder;
659  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
660  DepTL.setNameLoc(NameLoc);
662  DepTL.setQualifierLoc(QualifierLoc);
663  return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
664 }
665 
666 /// isTagName() - This method is called *for error recovery purposes only*
667 /// to determine if the specified name is a valid tag name ("struct foo"). If
668 /// so, this returns the TST for the tag corresponding to it (TST_enum,
669 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
670 /// cases in C where the user forgot to specify the tag.
672  // Do a tag name lookup in this scope.
673  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
674  LookupName(R, S, false);
677  if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
678  switch (TD->getTagKind()) {
679  case TTK_Struct: return DeclSpec::TST_struct;
681  case TTK_Union: return DeclSpec::TST_union;
682  case TTK_Class: return DeclSpec::TST_class;
683  case TTK_Enum: return DeclSpec::TST_enum;
684  }
685  }
686 
688 }
689 
690 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
691 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
692 /// then downgrade the missing typename error to a warning.
693 /// This is needed for MSVC compatibility; Example:
694 /// @code
695 /// template<class T> class A {
696 /// public:
697 /// typedef int TYPE;
698 /// };
699 /// template<class T> class B : public A<T> {
700 /// public:
701 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
702 /// };
703 /// @endcode
705  if (CurContext->isRecord()) {
707  return true;
708 
709  const Type *Ty = SS->getScopeRep()->getAsType();
710 
711  CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
712  for (const auto &Base : RD->bases())
713  if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
714  return true;
715  return S->isFunctionPrototypeScope();
716  }
717  return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
718 }
719 
721  SourceLocation IILoc,
722  Scope *S,
723  CXXScopeSpec *SS,
724  ParsedType &SuggestedType,
725  bool IsTemplateName) {
726  // Don't report typename errors for editor placeholders.
727  if (II->isEditorPlaceholder())
728  return;
729  // We don't have anything to suggest (yet).
730  SuggestedType = nullptr;
731 
732  // There may have been a typo in the name of the type. Look up typo
733  // results, in case we have something that we can suggest.
734  TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
735  /*AllowTemplates=*/IsTemplateName,
736  /*AllowNonTemplates=*/!IsTemplateName);
737  if (TypoCorrection Corrected =
738  CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
739  CCC, CTK_ErrorRecovery)) {
740  // FIXME: Support error recovery for the template-name case.
741  bool CanRecover = !IsTemplateName;
742  if (Corrected.isKeyword()) {
743  // We corrected to a keyword.
744  diagnoseTypo(Corrected,
745  PDiag(IsTemplateName ? diag::err_no_template_suggest
746  : diag::err_unknown_typename_suggest)
747  << II);
748  II = Corrected.getCorrectionAsIdentifierInfo();
749  } else {
750  // We found a similarly-named type or interface; suggest that.
751  if (!SS || !SS->isSet()) {
752  diagnoseTypo(Corrected,
753  PDiag(IsTemplateName ? diag::err_no_template_suggest
754  : diag::err_unknown_typename_suggest)
755  << II, CanRecover);
756  } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
757  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
758  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
759  II->getName().equals(CorrectedStr);
760  diagnoseTypo(Corrected,
761  PDiag(IsTemplateName
762  ? diag::err_no_member_template_suggest
763  : diag::err_unknown_nested_typename_suggest)
764  << II << DC << DroppedSpecifier << SS->getRange(),
765  CanRecover);
766  } else {
767  llvm_unreachable("could not have corrected a typo here");
768  }
769 
770  if (!CanRecover)
771  return;
772 
773  CXXScopeSpec tmpSS;
774  if (Corrected.getCorrectionSpecifier())
775  tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
776  SourceRange(IILoc));
777  // FIXME: Support class template argument deduction here.
778  SuggestedType =
779  getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
780  tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
781  /*IsCtorOrDtorName=*/false,
782  /*WantNontrivialTypeSourceInfo=*/true);
783  }
784  return;
785  }
786 
787  if (getLangOpts().CPlusPlus && !IsTemplateName) {
788  // See if II is a class template that the user forgot to pass arguments to.
789  UnqualifiedId Name;
790  Name.setIdentifier(II, IILoc);
791  CXXScopeSpec EmptySS;
792  TemplateTy TemplateResult;
793  bool MemberOfUnknownSpecialization;
794  if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
795  Name, nullptr, true, TemplateResult,
796  MemberOfUnknownSpecialization) == TNK_Type_template) {
797  diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
798  return;
799  }
800  }
801 
802  // FIXME: Should we move the logic that tries to recover from a missing tag
803  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
804 
805  if (!SS || (!SS->isSet() && !SS->isInvalid()))
806  Diag(IILoc, IsTemplateName ? diag::err_no_template
807  : diag::err_unknown_typename)
808  << II;
809  else if (DeclContext *DC = computeDeclContext(*SS, false))
810  Diag(IILoc, IsTemplateName ? diag::err_no_member_template
811  : diag::err_typename_nested_not_found)
812  << II << DC << SS->getRange();
813  else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
814  SuggestedType =
815  ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
816  } else if (isDependentScopeSpecifier(*SS)) {
817  unsigned DiagID = diag::err_typename_missing;
818  if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
819  DiagID = diag::ext_typename_missing;
820 
821  Diag(SS->getRange().getBegin(), DiagID)
822  << SS->getScopeRep() << II->getName()
823  << SourceRange(SS->getRange().getBegin(), IILoc)
824  << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
825  SuggestedType = ActOnTypenameType(S, SourceLocation(),
826  *SS, *II, IILoc).get();
827  } else {
828  assert(SS && SS->isInvalid() &&
829  "Invalid scope specifier has already been diagnosed");
830  }
831 }
832 
833 /// Determine whether the given result set contains either a type name
834 /// or
835 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
836  bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
837  NextToken.is(tok::less);
838 
839  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
840  if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
841  return true;
842 
843  if (CheckTemplate && isa<TemplateDecl>(*I))
844  return true;
845  }
846 
847  return false;
848 }
849 
850 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
851  Scope *S, CXXScopeSpec &SS,
852  IdentifierInfo *&Name,
853  SourceLocation NameLoc) {
854  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
855  SemaRef.LookupParsedName(R, S, &SS);
856  if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
857  StringRef FixItTagName;
858  switch (Tag->getTagKind()) {
859  case TTK_Class:
860  FixItTagName = "class ";
861  break;
862 
863  case TTK_Enum:
864  FixItTagName = "enum ";
865  break;
866 
867  case TTK_Struct:
868  FixItTagName = "struct ";
869  break;
870 
871  case TTK_Interface:
872  FixItTagName = "__interface ";
873  break;
874 
875  case TTK_Union:
876  FixItTagName = "union ";
877  break;
878  }
879 
880  StringRef TagName = FixItTagName.drop_back();
881  SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
882  << Name << TagName << SemaRef.getLangOpts().CPlusPlus
883  << FixItHint::CreateInsertion(NameLoc, FixItTagName);
884 
885  for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
886  I != IEnd; ++I)
887  SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
888  << Name << TagName;
889 
890  // Replace lookup results with just the tag decl.
891  Result.clear(Sema::LookupTagName);
892  SemaRef.LookupParsedName(Result, S, &SS);
893  return true;
894  }
895 
896  return false;
897 }
898 
900  IdentifierInfo *&Name,
901  SourceLocation NameLoc,
902  const Token &NextToken,
904  DeclarationNameInfo NameInfo(Name, NameLoc);
905  ObjCMethodDecl *CurMethod = getCurMethodDecl();
906 
907  assert(NextToken.isNot(tok::coloncolon) &&
908  "parse nested name specifiers before calling ClassifyName");
909  if (getLangOpts().CPlusPlus && SS.isSet() &&
910  isCurrentClassName(*Name, S, &SS)) {
911  // Per [class.qual]p2, this names the constructors of SS, not the
912  // injected-class-name. We don't have a classification for that.
913  // There's not much point caching this result, since the parser
914  // will reject it later.
916  }
917 
918  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
919  LookupParsedName(Result, S, &SS, !CurMethod);
920 
921  if (SS.isInvalid())
922  return NameClassification::Error();
923 
924  // For unqualified lookup in a class template in MSVC mode, look into
925  // dependent base classes where the primary class template is known.
926  if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
927  if (ParsedType TypeInBase =
928  recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
929  return TypeInBase;
930  }
931 
932  // Perform lookup for Objective-C instance variables (including automatically
933  // synthesized instance variables), if we're in an Objective-C method.
934  // FIXME: This lookup really, really needs to be folded in to the normal
935  // unqualified lookup mechanism.
936  if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
937  DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
938  if (Ivar.isInvalid())
939  return NameClassification::Error();
940  if (Ivar.isUsable())
941  return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
942 
943  // We defer builtin creation until after ivar lookup inside ObjC methods.
944  if (Result.empty())
945  LookupBuiltin(Result);
946  }
947 
948  bool SecondTry = false;
949  bool IsFilteredTemplateName = false;
950 
951 Corrected:
952  switch (Result.getResultKind()) {
954  // If an unqualified-id is followed by a '(', then we have a function
955  // call.
956  if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
957  // In C++, this is an ADL-only call.
958  // FIXME: Reference?
959  if (getLangOpts().CPlusPlus)
960  return NameClassification::UndeclaredNonType();
961 
962  // C90 6.3.2.2:
963  // If the expression that precedes the parenthesized argument list in a
964  // function call consists solely of an identifier, and if no
965  // declaration is visible for this identifier, the identifier is
966  // implicitly declared exactly as if, in the innermost block containing
967  // the function call, the declaration
968  //
969  // extern int identifier ();
970  //
971  // appeared.
972  //
973  // We also allow this in C99 as an extension. However, this is not
974  // allowed in all language modes as functions without prototypes may not
975  // be supported.
976  if (getLangOpts().implicitFunctionsAllowed()) {
977  if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
978  return NameClassification::NonType(D);
979  }
980  }
981 
982  if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
983  // In C++20 onwards, this could be an ADL-only call to a function
984  // template, and we're required to assume that this is a template name.
985  //
986  // FIXME: Find a way to still do typo correction in this case.
987  TemplateName Template =
988  Context.getAssumedTemplateName(NameInfo.getName());
989  return NameClassification::UndeclaredTemplate(Template);
990  }
991 
992  // In C, we first see whether there is a tag type by the same name, in
993  // which case it's likely that the user just forgot to write "enum",
994  // "struct", or "union".
995  if (!getLangOpts().CPlusPlus && !SecondTry &&
996  isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
997  break;
998  }
999 
1000  // Perform typo correction to determine if there is another name that is
1001  // close to this name.
1002  if (!SecondTry && CCC) {
1003  SecondTry = true;
1004  if (TypoCorrection Corrected =
1005  CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1006  &SS, *CCC, CTK_ErrorRecovery)) {
1007  unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1008  unsigned QualifiedDiag = diag::err_no_member_suggest;
1009 
1010  NamedDecl *FirstDecl = Corrected.getFoundDecl();
1011  NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1012  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1013  UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1014  UnqualifiedDiag = diag::err_no_template_suggest;
1015  QualifiedDiag = diag::err_no_member_template_suggest;
1016  } else if (UnderlyingFirstDecl &&
1017  (isa<TypeDecl>(UnderlyingFirstDecl) ||
1018  isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1019  isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1020  UnqualifiedDiag = diag::err_unknown_typename_suggest;
1021  QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1022  }
1023 
1024  if (SS.isEmpty()) {
1025  diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1026  } else {// FIXME: is this even reachable? Test it.
1027  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1028  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1029  Name->getName().equals(CorrectedStr);
1030  diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1031  << Name << computeDeclContext(SS, false)
1032  << DroppedSpecifier << SS.getRange());
1033  }
1034 
1035  // Update the name, so that the caller has the new name.
1036  Name = Corrected.getCorrectionAsIdentifierInfo();
1037 
1038  // Typo correction corrected to a keyword.
1039  if (Corrected.isKeyword())
1040  return Name;
1041 
1042  // Also update the LookupResult...
1043  // FIXME: This should probably go away at some point
1044  Result.clear();
1045  Result.setLookupName(Corrected.getCorrection());
1046  if (FirstDecl)
1047  Result.addDecl(FirstDecl);
1048 
1049  // If we found an Objective-C instance variable, let
1050  // LookupInObjCMethod build the appropriate expression to
1051  // reference the ivar.
1052  // FIXME: This is a gross hack.
1053  if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1054  DeclResult R =
1055  LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1056  if (R.isInvalid())
1057  return NameClassification::Error();
1058  if (R.isUsable())
1059  return NameClassification::NonType(Ivar);
1060  }
1061 
1062  goto Corrected;
1063  }
1064  }
1065 
1066  // We failed to correct; just fall through and let the parser deal with it.
1067  Result.suppressDiagnostics();
1068  return NameClassification::Unknown();
1069 
1071  // We performed name lookup into the current instantiation, and there were
1072  // dependent bases, so we treat this result the same way as any other
1073  // dependent nested-name-specifier.
1074 
1075  // C++ [temp.res]p2:
1076  // A name used in a template declaration or definition and that is
1077  // dependent on a template-parameter is assumed not to name a type
1078  // unless the applicable name lookup finds a type name or the name is
1079  // qualified by the keyword typename.
1080  //
1081  // FIXME: If the next token is '<', we might want to ask the parser to
1082  // perform some heroics to see if we actually have a
1083  // template-argument-list, which would indicate a missing 'template'
1084  // keyword here.
1085  return NameClassification::DependentNonType();
1086  }
1087 
1088  case LookupResult::Found:
1091  break;
1092 
1094  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1095  hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1096  /*AllowDependent=*/false)) {
1097  // C++ [temp.local]p3:
1098  // A lookup that finds an injected-class-name (10.2) can result in an
1099  // ambiguity in certain cases (for example, if it is found in more than
1100  // one base class). If all of the injected-class-names that are found
1101  // refer to specializations of the same class template, and if the name
1102  // is followed by a template-argument-list, the reference refers to the
1103  // class template itself and not a specialization thereof, and is not
1104  // ambiguous.
1105  //
1106  // This filtering can make an ambiguous result into an unambiguous one,
1107  // so try again after filtering out template names.
1108  FilterAcceptableTemplateNames(Result);
1109  if (!Result.isAmbiguous()) {
1110  IsFilteredTemplateName = true;
1111  break;
1112  }
1113  }
1114 
1115  // Diagnose the ambiguity and return an error.
1116  return NameClassification::Error();
1117  }
1118 
1119  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1120  (IsFilteredTemplateName ||
1121  hasAnyAcceptableTemplateNames(
1122  Result, /*AllowFunctionTemplates=*/true,
1123  /*AllowDependent=*/false,
1124  /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1125  getLangOpts().CPlusPlus20))) {
1126  // C++ [temp.names]p3:
1127  // After name lookup (3.4) finds that a name is a template-name or that
1128  // an operator-function-id or a literal- operator-id refers to a set of
1129  // overloaded functions any member of which is a function template if
1130  // this is followed by a <, the < is always taken as the delimiter of a
1131  // template-argument-list and never as the less-than operator.
1132  // C++2a [temp.names]p2:
1133  // A name is also considered to refer to a template if it is an
1134  // unqualified-id followed by a < and name lookup finds either one
1135  // or more functions or finds nothing.
1136  if (!IsFilteredTemplateName)
1137  FilterAcceptableTemplateNames(Result);
1138 
1139  bool IsFunctionTemplate;
1140  bool IsVarTemplate;
1141  TemplateName Template;
1142  if (Result.end() - Result.begin() > 1) {
1143  IsFunctionTemplate = true;
1144  Template = Context.getOverloadedTemplateName(Result.begin(),
1145  Result.end());
1146  } else if (!Result.empty()) {
1147  auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1148  *Result.begin(), /*AllowFunctionTemplates=*/true,
1149  /*AllowDependent=*/false));
1150  IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1151  IsVarTemplate = isa<VarTemplateDecl>(TD);
1152 
1153  UsingShadowDecl *FoundUsingShadow =
1154  dyn_cast<UsingShadowDecl>(*Result.begin());
1155  assert(!FoundUsingShadow ||
1156  TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1157  Template =
1158  FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1159  if (SS.isNotEmpty())
1160  Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1161  /*TemplateKeyword=*/false,
1162  Template);
1163  } else {
1164  // All results were non-template functions. This is a function template
1165  // name.
1166  IsFunctionTemplate = true;
1167  Template = Context.getAssumedTemplateName(NameInfo.getName());
1168  }
1169 
1170  if (IsFunctionTemplate) {
1171  // Function templates always go through overload resolution, at which
1172  // point we'll perform the various checks (e.g., accessibility) we need
1173  // to based on which function we selected.
1174  Result.suppressDiagnostics();
1175 
1176  return NameClassification::FunctionTemplate(Template);
1177  }
1178 
1179  return IsVarTemplate ? NameClassification::VarTemplate(Template)
1180  : NameClassification::TypeTemplate(Template);
1181  }
1182 
1183  auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1184  QualType T = Context.getTypeDeclType(Type);
1185  if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1186  T = Context.getUsingType(USD, T);
1187  return buildNamedType(*this, &SS, T, NameLoc);
1188  };
1189 
1190  NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1191  if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1192  DiagnoseUseOfDecl(Type, NameLoc);
1193  MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1194  return BuildTypeFor(Type, *Result.begin());
1195  }
1196 
1197  ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1198  if (!Class) {
1199  // FIXME: It's unfortunate that we don't have a Type node for handling this.
1200  if (ObjCCompatibleAliasDecl *Alias =
1201  dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1202  Class = Alias->getClassInterface();
1203  }
1204 
1205  if (Class) {
1206  DiagnoseUseOfDecl(Class, NameLoc);
1207 
1208  if (NextToken.is(tok::period)) {
1209  // Interface. <something> is parsed as a property reference expression.
1210  // Just return "unknown" as a fall-through for now.
1211  Result.suppressDiagnostics();
1212  return NameClassification::Unknown();
1213  }
1214 
1215  QualType T = Context.getObjCInterfaceType(Class);
1216  return ParsedType::make(T);
1217  }
1218 
1219  if (isa<ConceptDecl>(FirstDecl))
1220  return NameClassification::Concept(
1221  TemplateName(cast<TemplateDecl>(FirstDecl)));
1222 
1223  if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1224  (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1225  return NameClassification::Error();
1226  }
1227 
1228  // We can have a type template here if we're classifying a template argument.
1229  if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1230  !isa<VarTemplateDecl>(FirstDecl))
1231  return NameClassification::TypeTemplate(
1232  TemplateName(cast<TemplateDecl>(FirstDecl)));
1233 
1234  // Check for a tag type hidden by a non-type decl in a few cases where it
1235  // seems likely a type is wanted instead of the non-type that was found.
1236  bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1237  if ((NextToken.is(tok::identifier) ||
1238  (NextIsOp &&
1239  FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1240  isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1241  TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1242  DiagnoseUseOfDecl(Type, NameLoc);
1243  return BuildTypeFor(Type, *Result.begin());
1244  }
1245 
1246  // If we already know which single declaration is referenced, just annotate
1247  // that declaration directly. Defer resolving even non-overloaded class
1248  // member accesses, as we need to defer certain access checks until we know
1249  // the context.
1250  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1251  if (Result.isSingleResult() && !ADL &&
1252  (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1253  return NameClassification::NonType(Result.getRepresentativeDecl());
1254 
1255  // Otherwise, this is an overload set that we will need to resolve later.
1256  Result.suppressDiagnostics();
1257  return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1258  Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1259  Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1260  Result.begin(), Result.end()));
1261 }
1262 
1263 ExprResult
1265  SourceLocation NameLoc) {
1266  assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1267  CXXScopeSpec SS;
1268  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1269  return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1270 }
1271 
1272 ExprResult
1274  IdentifierInfo *Name,
1275  SourceLocation NameLoc,
1276  bool IsAddressOfOperand) {
1277  DeclarationNameInfo NameInfo(Name, NameLoc);
1278  return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1279  NameInfo, IsAddressOfOperand,
1280  /*TemplateArgs=*/nullptr);
1281 }
1282 
1284  NamedDecl *Found,
1285  SourceLocation NameLoc,
1286  const Token &NextToken) {
1287  if (getCurMethodDecl() && SS.isEmpty())
1288  if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1289  return BuildIvarRefExpr(S, NameLoc, Ivar);
1290 
1291  // Reconstruct the lookup result.
1292  LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1293  Result.addDecl(Found);
1294  Result.resolveKind();
1295 
1296  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1297  return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1298 }
1299 
1301  // For an implicit class member access, transform the result into a member
1302  // access expression if necessary.
1303  auto *ULE = cast<UnresolvedLookupExpr>(E);
1304  if ((*ULE->decls_begin())->isCXXClassMember()) {
1305  CXXScopeSpec SS;
1306  SS.Adopt(ULE->getQualifierLoc());
1307 
1308  // Reconstruct the lookup result.
1309  LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1310  LookupOrdinaryName);
1311  Result.setNamingClass(ULE->getNamingClass());
1312  for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1313  Result.addDecl(*I, I.getAccess());
1314  Result.resolveKind();
1315  return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1316  nullptr, S);
1317  }
1318 
1319  // Otherwise, this is already in the form we needed, and no further checks
1320  // are necessary.
1321  return ULE;
1322 }
1323 
1326  auto *TD = Name.getAsTemplateDecl();
1327  if (!TD)
1328  return TemplateNameKindForDiagnostics::DependentTemplate;
1329  if (isa<ClassTemplateDecl>(TD))
1330  return TemplateNameKindForDiagnostics::ClassTemplate;
1331  if (isa<FunctionTemplateDecl>(TD))
1332  return TemplateNameKindForDiagnostics::FunctionTemplate;
1333  if (isa<VarTemplateDecl>(TD))
1334  return TemplateNameKindForDiagnostics::VarTemplate;
1335  if (isa<TypeAliasTemplateDecl>(TD))
1336  return TemplateNameKindForDiagnostics::AliasTemplate;
1337  if (isa<TemplateTemplateParmDecl>(TD))
1338  return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1339  if (isa<ConceptDecl>(TD))
1340  return TemplateNameKindForDiagnostics::Concept;
1341  return TemplateNameKindForDiagnostics::DependentTemplate;
1342 }
1343 
1345  assert(DC->getLexicalParent() == CurContext &&
1346  "The next DeclContext should be lexically contained in the current one.");
1347  CurContext = DC;
1348  S->setEntity(DC);
1349 }
1350 
1352  assert(CurContext && "DeclContext imbalance!");
1353 
1354  CurContext = CurContext->getLexicalParent();
1355  assert(CurContext && "Popped translation unit!");
1356 }
1357 
1359  Decl *D) {
1360  // Unlike PushDeclContext, the context to which we return is not necessarily
1361  // the containing DC of TD, because the new context will be some pre-existing
1362  // TagDecl definition instead of a fresh one.
1363  auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1364  CurContext = cast<TagDecl>(D)->getDefinition();
1365  assert(CurContext && "skipping definition of undefined tag");
1366  // Start lookups from the parent of the current context; we don't want to look
1367  // into the pre-existing complete definition.
1368  S->setEntity(CurContext->getLookupParent());
1369  return Result;
1370 }
1371 
1373  CurContext = static_cast<decltype(CurContext)>(Context);
1374 }
1375 
1376 /// EnterDeclaratorContext - Used when we must lookup names in the context
1377 /// of a declarator's nested name specifier.
1378 ///
1380  // C++0x [basic.lookup.unqual]p13:
1381  // A name used in the definition of a static data member of class
1382  // X (after the qualified-id of the static member) is looked up as
1383  // if the name was used in a member function of X.
1384  // C++0x [basic.lookup.unqual]p14:
1385  // If a variable member of a namespace is defined outside of the
1386  // scope of its namespace then any name used in the definition of
1387  // the variable member (after the declarator-id) is looked up as
1388  // if the definition of the variable member occurred in its
1389  // namespace.
1390  // Both of these imply that we should push a scope whose context
1391  // is the semantic context of the declaration. We can't use
1392  // PushDeclContext here because that context is not necessarily
1393  // lexically contained in the current context. Fortunately,
1394  // the containing scope should have the appropriate information.
1395 
1396  assert(!S->getEntity() && "scope already has entity");
1397 
1398 #ifndef NDEBUG
1399  Scope *Ancestor = S->getParent();
1400  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1401  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1402 #endif
1403 
1404  CurContext = DC;
1405  S->setEntity(DC);
1406 
1407  if (S->getParent()->isTemplateParamScope()) {
1408  // Also set the corresponding entities for all immediately-enclosing
1409  // template parameter scopes.
1410  EnterTemplatedContext(S->getParent(), DC);
1411  }
1412 }
1413 
1415  assert(S->getEntity() == CurContext && "Context imbalance!");
1416 
1417  // Switch back to the lexical context. The safety of this is
1418  // enforced by an assert in EnterDeclaratorContext.
1419  Scope *Ancestor = S->getParent();
1420  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1421  CurContext = Ancestor->getEntity();
1422 
1423  // We don't need to do anything with the scope, which is going to
1424  // disappear.
1425 }
1426 
1428  assert(S->isTemplateParamScope() &&
1429  "expected to be initializing a template parameter scope");
1430 
1431  // C++20 [temp.local]p7:
1432  // In the definition of a member of a class template that appears outside
1433  // of the class template definition, the name of a member of the class
1434  // template hides the name of a template-parameter of any enclosing class
1435  // templates (but not a template-parameter of the member if the member is a
1436  // class or function template).
1437  // C++20 [temp.local]p9:
1438  // In the definition of a class template or in the definition of a member
1439  // of such a template that appears outside of the template definition, for
1440  // each non-dependent base class (13.8.2.1), if the name of the base class
1441  // or the name of a member of the base class is the same as the name of a
1442  // template-parameter, the base class name or member name hides the
1443  // template-parameter name (6.4.10).
1444  //
1445  // This means that a template parameter scope should be searched immediately
1446  // after searching the DeclContext for which it is a template parameter
1447  // scope. For example, for
1448  // template<typename T> template<typename U> template<typename V>
1449  // void N::A<T>::B<U>::f(...)
1450  // we search V then B<U> (and base classes) then U then A<T> (and base
1451  // classes) then T then N then ::.
1452  unsigned ScopeDepth = getTemplateDepth(S);
1453  for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1454  DeclContext *SearchDCAfterScope = DC;
1455  for (; DC; DC = DC->getLookupParent()) {
1456  if (const TemplateParameterList *TPL =
1457  cast<Decl>(DC)->getDescribedTemplateParams()) {
1458  unsigned DCDepth = TPL->getDepth() + 1;
1459  if (DCDepth > ScopeDepth)
1460  continue;
1461  if (ScopeDepth == DCDepth)
1462  SearchDCAfterScope = DC = DC->getLookupParent();
1463  break;
1464  }
1465  }
1466  S->setLookupEntity(SearchDCAfterScope);
1467  }
1468 }
1469 
1471  // We assume that the caller has already called
1472  // ActOnReenterTemplateScope so getTemplatedDecl() works.
1473  FunctionDecl *FD = D->getAsFunction();
1474  if (!FD)
1475  return;
1476 
1477  // Same implementation as PushDeclContext, but enters the context
1478  // from the lexical parent, rather than the top-level class.
1479  assert(CurContext == FD->getLexicalParent() &&
1480  "The next DeclContext should be lexically contained in the current one.");
1481  CurContext = FD;
1482  S->setEntity(CurContext);
1483 
1484  for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1485  ParmVarDecl *Param = FD->getParamDecl(P);
1486  // If the parameter has an identifier, then add it to the scope
1487  if (Param->getIdentifier()) {
1488  S->AddDecl(Param);
1489  IdResolver.AddDecl(Param);
1490  }
1491  }
1492 }
1493 
1495  // Same implementation as PopDeclContext, but returns to the lexical parent,
1496  // rather than the top-level class.
1497  assert(CurContext && "DeclContext imbalance!");
1498  CurContext = CurContext->getLexicalParent();
1499  assert(CurContext && "Popped translation unit!");
1500 }
1501 
1502 /// Determine whether overloading is allowed for a new function
1503 /// declaration considering prior declarations of the same name.
1504 ///
1505 /// This routine determines whether overloading is possible, not
1506 /// whether a new declaration actually overloads a previous one.
1507 /// It will return true in C++ (where overloads are alway permitted)
1508 /// or, as a C extension, when either the new declaration or a
1509 /// previous one is declared with the 'overloadable' attribute.
1511  ASTContext &Context,
1512  const FunctionDecl *New) {
1513  if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1514  return true;
1515 
1516  // Multiversion function declarations are not overloads in the
1517  // usual sense of that term, but lookup will report that an
1518  // overload set was found if more than one multiversion function
1519  // declaration is present for the same name. It is therefore
1520  // inadequate to assume that some prior declaration(s) had
1521  // the overloadable attribute; checking is required. Since one
1522  // declaration is permitted to omit the attribute, it is necessary
1523  // to check at least two; hence the 'any_of' check below. Note that
1524  // the overloadable attribute is implicitly added to declarations
1525  // that were required to have it but did not.
1526  if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1527  return llvm::any_of(Previous, [](const NamedDecl *ND) {
1528  return ND->hasAttr<OverloadableAttr>();
1529  });
1530  } else if (Previous.getResultKind() == LookupResult::Found)
1531  return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1532 
1533  return false;
1534 }
1535 
1536 /// Add this decl to the scope shadowed decl chains.
1537 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1538  // Move up the scope chain until we find the nearest enclosing
1539  // non-transparent context. The declaration will be introduced into this
1540  // scope.
1541  while (S->getEntity() && S->getEntity()->isTransparentContext())
1542  S = S->getParent();
1543 
1544  // Add scoped declarations into their context, so that they can be
1545  // found later. Declarations without a context won't be inserted
1546  // into any context.
1547  if (AddToContext)
1548  CurContext->addDecl(D);
1549 
1550  // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1551  // are function-local declarations.
1552  if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1553  return;
1554 
1555  // Template instantiations should also not be pushed into scope.
1556  if (isa<FunctionDecl>(D) &&
1557  cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1558  return;
1559 
1560  // If this replaces anything in the current scope,
1561  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1562  IEnd = IdResolver.end();
1563  for (; I != IEnd; ++I) {
1564  if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1565  S->RemoveDecl(*I);
1566  IdResolver.RemoveDecl(*I);
1567 
1568  // Should only need to replace one decl.
1569  break;
1570  }
1571  }
1572 
1573  S->AddDecl(D);
1574 
1575  if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1576  // Implicitly-generated labels may end up getting generated in an order that
1577  // isn't strictly lexical, which breaks name lookup. Be careful to insert
1578  // the label at the appropriate place in the identifier chain.
1579  for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1580  DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1581  if (IDC == CurContext) {
1582  if (!S->isDeclScope(*I))
1583  continue;
1584  } else if (IDC->Encloses(CurContext))
1585  break;
1586  }
1587 
1588  IdResolver.InsertDeclAfter(I, D);
1589  } else {
1590  IdResolver.AddDecl(D);
1591  }
1592  warnOnReservedIdentifier(D);
1593 }
1594 
1596  bool AllowInlineNamespace) {
1597  return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1598 }
1599 
1601  DeclContext *TargetDC = DC->getPrimaryContext();
1602  do {
1603  if (DeclContext *ScopeDC = S->getEntity())
1604  if (ScopeDC->getPrimaryContext() == TargetDC)
1605  return S;
1606  } while ((S = S->getParent()));
1607 
1608  return nullptr;
1609 }
1610 
1612  DeclContext*,
1613  ASTContext&);
1614 
1615 /// Filters out lookup results that don't fall within the given scope
1616 /// as determined by isDeclInScope.
1618  bool ConsiderLinkage,
1619  bool AllowInlineNamespace) {
1621  while (F.hasNext()) {
1622  NamedDecl *D = F.next();
1623 
1624  if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1625  continue;
1626 
1627  if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1628  continue;
1629 
1630  F.erase();
1631  }
1632 
1633  F.done();
1634 }
1635 
1636 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1637 /// have compatible owning modules.
1639  // [module.interface]p7:
1640  // A declaration is attached to a module as follows:
1641  // - If the declaration is a non-dependent friend declaration that nominates a
1642  // function with a declarator-id that is a qualified-id or template-id or that
1643  // nominates a class other than with an elaborated-type-specifier with neither
1644  // a nested-name-specifier nor a simple-template-id, it is attached to the
1645  // module to which the friend is attached ([basic.link]).
1646  if (New->getFriendObjectKind() &&
1649  makeMergedDefinitionVisible(New);
1650  return false;
1651  }
1652 
1653  Module *NewM = New->getOwningModule();
1654  Module *OldM = Old->getOwningModule();
1655 
1656  if (NewM && NewM->isPrivateModule())
1657  NewM = NewM->Parent;
1658  if (OldM && OldM->isPrivateModule())
1659  OldM = OldM->Parent;
1660 
1661  if (NewM == OldM)
1662  return false;
1663 
1664  // Partitions are part of the module, but a partition could import another
1665  // module, so verify that the PMIs agree.
1666  if (NewM && OldM &&
1667  (NewM->isModulePartition() || OldM->isModulePartition()) &&
1670  return false;
1671 
1672  bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1673  bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1674  if (NewIsModuleInterface || OldIsModuleInterface) {
1675  // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1676  // if a declaration of D [...] appears in the purview of a module, all
1677  // other such declarations shall appear in the purview of the same module
1678  Diag(New->getLocation(), diag::err_mismatched_owning_module)
1679  << New
1680  << NewIsModuleInterface
1681  << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1682  << OldIsModuleInterface
1683  << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1684  Diag(Old->getLocation(), diag::note_previous_declaration);
1685  New->setInvalidDecl();
1686  return true;
1687  }
1688 
1689  return false;
1690 }
1691 
1692 // [module.interface]p6:
1693 // A redeclaration of an entity X is implicitly exported if X was introduced by
1694 // an exported declaration; otherwise it shall not be exported.
1696  // [module.interface]p1:
1697  // An export-declaration shall inhabit a namespace scope.
1698  //
1699  // So it is meaningless to talk about redeclaration which is not at namespace
1700  // scope.
1701  if (!New->getLexicalDeclContext()
1703  ->isFileContext() ||
1704  !Old->getLexicalDeclContext()
1706  ->isFileContext())
1707  return false;
1708 
1709  bool IsNewExported = New->isInExportDeclContext();
1710  bool IsOldExported = Old->isInExportDeclContext();
1711 
1712  // It should be irrevelant if both of them are not exported.
1713  if (!IsNewExported && !IsOldExported)
1714  return false;
1715 
1716  if (IsOldExported)
1717  return false;
1718 
1719  assert(IsNewExported);
1720 
1721  auto Lk = Old->getFormalLinkage();
1722  int S = 0;
1723  if (Lk == Linkage::InternalLinkage)
1724  S = 1;
1725  else if (Lk == Linkage::ModuleLinkage)
1726  S = 2;
1727  Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1728  Diag(Old->getLocation(), diag::note_previous_declaration);
1729  return true;
1730 }
1731 
1732 // A wrapper function for checking the semantic restrictions of
1733 // a redeclaration within a module.
1735  if (CheckRedeclarationModuleOwnership(New, Old))
1736  return true;
1737 
1738  if (CheckRedeclarationExported(New, Old))
1739  return true;
1740 
1741  return false;
1742 }
1743 
1744 // Check the redefinition in C++20 Modules.
1745 //
1746 // [basic.def.odr]p14:
1747 // For any definable item D with definitions in multiple translation units,
1748 // - if D is a non-inline non-templated function or variable, or
1749 // - if the definitions in different translation units do not satisfy the
1750 // following requirements,
1751 // the program is ill-formed; a diagnostic is required only if the definable
1752 // item is attached to a named module and a prior definition is reachable at
1753 // the point where a later definition occurs.
1754 // - Each such definition shall not be attached to a named module
1755 // ([module.unit]).
1756 // - Each such definition shall consist of the same sequence of tokens, ...
1757 // ...
1758 //
1759 // Return true if the redefinition is not allowed. Return false otherwise.
1761  const NamedDecl *Old) const {
1762  assert(getASTContext().isSameEntity(New, Old) &&
1763  "New and Old are not the same definition, we should diagnostic it "
1764  "immediately instead of checking it.");
1765  assert(const_cast<Sema *>(this)->isReachable(New) &&
1766  const_cast<Sema *>(this)->isReachable(Old) &&
1767  "We shouldn't see unreachable definitions here.");
1768 
1769  Module *NewM = New->getOwningModule();
1770  Module *OldM = Old->getOwningModule();
1771 
1772  // We only checks for named modules here. The header like modules is skipped.
1773  // FIXME: This is not right if we import the header like modules in the module
1774  // purview.
1775  //
1776  // For example, assuming "header.h" provides definition for `D`.
1777  // ```C++
1778  // //--- M.cppm
1779  // export module M;
1780  // import "header.h"; // or #include "header.h" but import it by clang modules
1781  // actually.
1782  //
1783  // //--- Use.cpp
1784  // import M;
1785  // import "header.h"; // or uses clang modules.
1786  // ```
1787  //
1788  // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1789  // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1790  // reject it. But the current implementation couldn't detect the case since we
1791  // don't record the information about the importee modules.
1792  //
1793  // But this might not be painful in practice. Since the design of C++20 Named
1794  // Modules suggests us to use headers in global module fragment instead of
1795  // module purview.
1796  if (NewM && NewM->isHeaderLikeModule())
1797  NewM = nullptr;
1798  if (OldM && OldM->isHeaderLikeModule())
1799  OldM = nullptr;
1800 
1801  if (!NewM && !OldM)
1802  return true;
1803 
1804  // [basic.def.odr]p14.3
1805  // Each such definition shall not be attached to a named module
1806  // ([module.unit]).
1807  if ((NewM && NewM->isModulePurview()) || (OldM && OldM->isModulePurview()))
1808  return true;
1809 
1810  // Then New and Old lives in the same TU if their share one same module unit.
1811  if (NewM)
1812  NewM = NewM->getTopLevelModule();
1813  if (OldM)
1814  OldM = OldM->getTopLevelModule();
1815  return OldM == NewM;
1816 }
1817 
1818 static bool isUsingDecl(NamedDecl *D) {
1819  return isa<UsingShadowDecl>(D) ||
1820  isa<UnresolvedUsingTypenameDecl>(D) ||
1821  isa<UnresolvedUsingValueDecl>(D);
1822 }
1823 
1824 /// Removes using shadow declarations from the lookup results.
1827  while (F.hasNext())
1828  if (isUsingDecl(F.next()))
1829  F.erase();
1830 
1831  F.done();
1832 }
1833 
1834 /// Check for this common pattern:
1835 /// @code
1836 /// class S {
1837 /// S(const S&); // DO NOT IMPLEMENT
1838 /// void operator=(const S&); // DO NOT IMPLEMENT
1839 /// };
1840 /// @endcode
1842  // FIXME: Should check for private access too but access is set after we get
1843  // the decl here.
1845  return false;
1846 
1847  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1848  return CD->isCopyConstructor();
1849  return D->isCopyAssignmentOperator();
1850 }
1851 
1852 // We need this to handle
1853 //
1854 // typedef struct {
1855 // void *foo() { return 0; }
1856 // } A;
1857 //
1858 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1859 // for example. If 'A', foo will have external linkage. If we have '*A',
1860 // foo will have no linkage. Since we can't know until we get to the end
1861 // of the typedef, this function finds out if D might have non-external linkage.
1862 // Callers should verify at the end of the TU if it D has external linkage or
1863 // not.
1864 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1865  const DeclContext *DC = D->getDeclContext();
1866  while (!DC->isTranslationUnit()) {
1867  if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1868  if (!RD->hasNameForLinkage())
1869  return true;
1870  }
1871  DC = DC->getParent();
1872  }
1873 
1874  return !D->isExternallyVisible();
1875 }
1876 
1877 // FIXME: This needs to be refactored; some other isInMainFile users want
1878 // these semantics.
1879 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1880  if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1881  return false;
1882  return S.SourceMgr.isInMainFile(Loc);
1883 }
1884 
1886  assert(D);
1887 
1888  if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1889  return false;
1890 
1891  // Ignore all entities declared within templates, and out-of-line definitions
1892  // of members of class templates.
1893  if (D->getDeclContext()->isDependentContext() ||
1895  return false;
1896 
1897  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1898  if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1899  return false;
1900  // A non-out-of-line declaration of a member specialization was implicitly
1901  // instantiated; it's the out-of-line declaration that we're interested in.
1902  if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1903  FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1904  return false;
1905 
1906  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1907  if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1908  return false;
1909  } else {
1910  // 'static inline' functions are defined in headers; don't warn.
1911  if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1912  return false;
1913  }
1914 
1915  if (FD->doesThisDeclarationHaveABody() &&
1916  Context.DeclMustBeEmitted(FD))
1917  return false;
1918  } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1919  // Constants and utility variables are defined in headers with internal
1920  // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1921  // like "inline".)
1922  if (!isMainFileLoc(*this, VD->getLocation()))
1923  return false;
1924 
1925  if (Context.DeclMustBeEmitted(VD))
1926  return false;
1927 
1928  if (VD->isStaticDataMember() &&
1929  VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1930  return false;
1931  if (VD->isStaticDataMember() &&
1932  VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1933  VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1934  return false;
1935 
1936  if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1937  return false;
1938  } else {
1939  return false;
1940  }
1941 
1942  // Only warn for unused decls internal to the translation unit.
1943  // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1944  // for inline functions defined in the main source file, for instance.
1945  return mightHaveNonExternalLinkage(D);
1946 }
1947 
1949  if (!D)
1950  return;
1951 
1952  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1953  const FunctionDecl *First = FD->getFirstDecl();
1954  if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1955  return; // First should already be in the vector.
1956  }
1957 
1958  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1959  const VarDecl *First = VD->getFirstDecl();
1960  if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1961  return; // First should already be in the vector.
1962  }
1963 
1964  if (ShouldWarnIfUnusedFileScopedDecl(D))
1965  UnusedFileScopedDecls.push_back(D);
1966 }
1967 
1968 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1969  if (D->isInvalidDecl())
1970  return false;
1971 
1972  if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1973  // For a decomposition declaration, warn if none of the bindings are
1974  // referenced, instead of if the variable itself is referenced (which
1975  // it is, by the bindings' expressions).
1976  for (auto *BD : DD->bindings())
1977  if (BD->isReferenced())
1978  return false;
1979  } else if (!D->getDeclName()) {
1980  return false;
1981  } else if (D->isReferenced() || D->isUsed()) {
1982  return false;
1983  }
1984 
1985  if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1986  return false;
1987 
1988  if (isa<LabelDecl>(D))
1989  return true;
1990 
1991  // Except for labels, we only care about unused decls that are local to
1992  // functions.
1993  bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1994  if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1995  // For dependent types, the diagnostic is deferred.
1996  WithinFunction =
1997  WithinFunction || (R->isLocalClass() && !R->isDependentType());
1998  if (!WithinFunction)
1999  return false;
2000 
2001  if (isa<TypedefNameDecl>(D))
2002  return true;
2003 
2004  // White-list anything that isn't a local variable.
2005  if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
2006  return false;
2007 
2008  // Types of valid local variables should be complete, so this should succeed.
2009  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2010 
2011  const Expr *Init = VD->getInit();
2012  if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
2013  Init = Cleanups->getSubExpr();
2014 
2015  const auto *Ty = VD->getType().getTypePtr();
2016 
2017  // Only look at the outermost level of typedef.
2018  if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2019  // Allow anything marked with __attribute__((unused)).
2020  if (TT->getDecl()->hasAttr<UnusedAttr>())
2021  return false;
2022  }
2023 
2024  // Warn for reference variables whose initializtion performs lifetime
2025  // extension.
2026  if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
2027  if (MTE->getExtendingDecl()) {
2028  Ty = VD->getType().getNonReferenceType().getTypePtr();
2029  Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2030  }
2031  }
2032 
2033  // If we failed to complete the type for some reason, or if the type is
2034  // dependent, don't diagnose the variable.
2035  if (Ty->isIncompleteType() || Ty->isDependentType())
2036  return false;
2037 
2038  // Look at the element type to ensure that the warning behaviour is
2039  // consistent for both scalars and arrays.
2040  Ty = Ty->getBaseElementTypeUnsafe();
2041 
2042  if (const TagType *TT = Ty->getAs<TagType>()) {
2043  const TagDecl *Tag = TT->getDecl();
2044  if (Tag->hasAttr<UnusedAttr>())
2045  return false;
2046 
2047  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2048  if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2049  return false;
2050 
2051  if (Init) {
2052  const CXXConstructExpr *Construct =
2053  dyn_cast<CXXConstructExpr>(Init);
2054  if (Construct && !Construct->isElidable()) {
2055  CXXConstructorDecl *CD = Construct->getConstructor();
2056  if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2057  (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2058  return false;
2059  }
2060 
2061  // Suppress the warning if we don't know how this is constructed, and
2062  // it could possibly be non-trivial constructor.
2063  if (Init->isTypeDependent()) {
2064  for (const CXXConstructorDecl *Ctor : RD->ctors())
2065  if (!Ctor->isTrivial())
2066  return false;
2067  }
2068 
2069  // Suppress the warning if the constructor is unresolved because
2070  // its arguments are dependent.
2071  if (isa<CXXUnresolvedConstructExpr>(Init))
2072  return false;
2073  }
2074  }
2075  }
2076 
2077  // TODO: __attribute__((unused)) templates?
2078  }
2079 
2080  return true;
2081 }
2082 
2083 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2084  FixItHint &Hint) {
2085  if (isa<LabelDecl>(D)) {
2087  D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2088  true);
2089  if (AfterColon.isInvalid())
2090  return;
2091  Hint = FixItHint::CreateRemoval(
2092  CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2093  }
2094 }
2095 
2097  DiagnoseUnusedNestedTypedefs(
2098  D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2099 }
2100 
2102  DiagReceiverTy DiagReceiver) {
2103  if (D->getTypeForDecl()->isDependentType())
2104  return;
2105 
2106  for (auto *TmpD : D->decls()) {
2107  if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2108  DiagnoseUnusedDecl(T, DiagReceiver);
2109  else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2110  DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2111  }
2112 }
2113 
2115  DiagnoseUnusedDecl(
2116  D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2117 }
2118 
2119 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2120 /// unless they are marked attr(unused).
2121 void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2122  if (!ShouldDiagnoseUnusedDecl(D))
2123  return;
2124 
2125  if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2126  // typedefs can be referenced later on, so the diagnostics are emitted
2127  // at end-of-translation-unit.
2128  UnusedLocalTypedefNameCandidates.insert(TD);
2129  return;
2130  }
2131 
2132  FixItHint Hint;
2133  GenerateFixForUnusedDecl(D, Context, Hint);
2134 
2135  unsigned DiagID;
2136  if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2137  DiagID = diag::warn_unused_exception_param;
2138  else if (isa<LabelDecl>(D))
2139  DiagID = diag::warn_unused_label;
2140  else
2141  DiagID = diag::warn_unused_variable;
2142 
2143  DiagReceiver(D->getLocation(), PDiag(DiagID) << D << Hint);
2144 }
2145 
2147  DiagReceiverTy DiagReceiver) {
2148  // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2149  // it's not really unused.
2150  if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2151  VD->hasAttr<CleanupAttr>())
2152  return;
2153 
2154  const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2155 
2156  if (Ty->isReferenceType() || Ty->isDependentType())
2157  return;
2158 
2159  if (const TagType *TT = Ty->getAs<TagType>()) {
2160  const TagDecl *Tag = TT->getDecl();
2161  if (Tag->hasAttr<UnusedAttr>())
2162  return;
2163  // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2164  // mimic gcc's behavior.
2165  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2166  if (!RD->hasAttr<WarnUnusedAttr>())
2167  return;
2168  }
2169  }
2170 
2171  // Don't warn about __block Objective-C pointer variables, as they might
2172  // be assigned in the block but not used elsewhere for the purpose of lifetime
2173  // extension.
2174  if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2175  return;
2176 
2177  // Don't warn about Objective-C pointer variables with precise lifetime
2178  // semantics; they can be used to ensure ARC releases the object at a known
2179  // time, which may mean assignment but no other references.
2180  if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2181  return;
2182 
2183  auto iter = RefsMinusAssignments.find(VD);
2184  if (iter == RefsMinusAssignments.end())
2185  return;
2186 
2187  assert(iter->getSecond() >= 0 &&
2188  "Found a negative number of references to a VarDecl");
2189  if (iter->getSecond() != 0)
2190  return;
2191  unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2192  : diag::warn_unused_but_set_variable;
2193  DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2194 }
2195 
2196 static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2197  Sema::DiagReceiverTy DiagReceiver) {
2198  // Verify that we have no forward references left. If so, there was a goto
2199  // or address of a label taken, but no definition of it. Label fwd
2200  // definitions are indicated with a null substmt which is also not a resolved
2201  // MS inline assembly label name.
2202  bool Diagnose = false;
2203  if (L->isMSAsmLabel())
2204  Diagnose = !L->isResolvedMSAsmLabel();
2205  else
2206  Diagnose = L->getStmt() == nullptr;
2207  if (Diagnose)
2208  DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2209  << L);
2210 }
2211 
2213  S->applyNRVO();
2214 
2215  if (S->decl_empty()) return;
2216  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2217  "Scope shouldn't contain decls!");
2218 
2219  /// We visit the decls in non-deterministic order, but we want diagnostics
2220  /// emitted in deterministic order. Collect any diagnostic that may be emitted
2221  /// and sort the diagnostics before emitting them, after we visited all decls.
2222  struct LocAndDiag {
2223  SourceLocation Loc;
2224  std::optional<SourceLocation> PreviousDeclLoc;
2225  PartialDiagnostic PD;
2226  };
2227  SmallVector<LocAndDiag, 16> DeclDiags;
2228  auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2229  DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2230  };
2231  auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2232  SourceLocation PreviousDeclLoc,
2233  PartialDiagnostic PD) {
2234  DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2235  };
2236 
2237  for (auto *TmpD : S->decls()) {
2238  assert(TmpD && "This decl didn't get pushed??");
2239 
2240  assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2241  NamedDecl *D = cast<NamedDecl>(TmpD);
2242 
2243  // Diagnose unused variables in this scope.
2244  if (!S->hasUnrecoverableErrorOccurred()) {
2245  DiagnoseUnusedDecl(D, addDiag);
2246  if (const auto *RD = dyn_cast<RecordDecl>(D))
2247  DiagnoseUnusedNestedTypedefs(RD, addDiag);
2248  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2249  DiagnoseUnusedButSetDecl(VD, addDiag);
2250  RefsMinusAssignments.erase(VD);
2251  }
2252  }
2253 
2254  if (!D->getDeclName()) continue;
2255 
2256  // If this was a forward reference to a label, verify it was defined.
2257  if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2258  CheckPoppedLabel(LD, *this, addDiag);
2259 
2260  // Remove this name from our lexical scope, and warn on it if we haven't
2261  // already.
2262  IdResolver.RemoveDecl(D);
2263  auto ShadowI = ShadowingDecls.find(D);
2264  if (ShadowI != ShadowingDecls.end()) {
2265  if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2266  addDiagWithPrev(D->getLocation(), FD->getLocation(),
2267  PDiag(diag::warn_ctor_parm_shadows_field)
2268  << D << FD << FD->getParent());
2269  }
2270  ShadowingDecls.erase(ShadowI);
2271  }
2272  }
2273 
2274  llvm::sort(DeclDiags,
2275  [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2276  // The particular order for diagnostics is not important, as long
2277  // as the order is deterministic. Using the raw location is going
2278  // to generally be in source order unless there are macro
2279  // expansions involved.
2280  return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2281  });
2282  for (const LocAndDiag &D : DeclDiags) {
2283  Diag(D.Loc, D.PD);
2284  if (D.PreviousDeclLoc)
2285  Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2286  }
2287 }
2288 
2289 /// Look for an Objective-C class in the translation unit.
2290 ///
2291 /// \param Id The name of the Objective-C class we're looking for. If
2292 /// typo-correction fixes this name, the Id will be updated
2293 /// to the fixed name.
2294 ///
2295 /// \param IdLoc The location of the name in the translation unit.
2296 ///
2297 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2298 /// if there is no class with the given name.
2299 ///
2300 /// \returns The declaration of the named Objective-C class, or NULL if the
2301 /// class could not be found.
2303  SourceLocation IdLoc,
2304  bool DoTypoCorrection) {
2305  // The third "scope" argument is 0 since we aren't enabling lazy built-in
2306  // creation from this context.
2307  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2308 
2309  if (!IDecl && DoTypoCorrection) {
2310  // Perform typo correction at the given location, but only if we
2311  // find an Objective-C class name.
2313  if (TypoCorrection C =
2314  CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2315  TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2316  diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2317  IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2318  Id = IDecl->getIdentifier();
2319  }
2320  }
2321  ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2322  // This routine must always return a class definition, if any.
2323  if (Def && Def->getDefinition())
2324  Def = Def->getDefinition();
2325  return Def;
2326 }
2327 
2328 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2329 /// from S, where a non-field would be declared. This routine copes
2330 /// with the difference between C and C++ scoping rules in structs and
2331 /// unions. For example, the following code is well-formed in C but
2332 /// ill-formed in C++:
2333 /// @code
2334 /// struct S6 {
2335 /// enum { BAR } e;
2336 /// };
2337 ///
2338 /// void test_S6() {
2339 /// struct S6 a;
2340 /// a.e = BAR;
2341 /// }
2342 /// @endcode
2343 /// For the declaration of BAR, this routine will return a different
2344 /// scope. The scope S will be the scope of the unnamed enumeration
2345 /// within S6. In C++, this routine will return the scope associated
2346 /// with S6, because the enumeration's scope is a transparent
2347 /// context but structures can contain non-field names. In C, this
2348 /// routine will return the translation unit scope, since the
2349 /// enumeration's scope is a transparent context and structures cannot
2350 /// contain non-field names.
2352  while (((S->getFlags() & Scope::DeclScope) == 0) ||
2353  (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2354  (S->isClassScope() && !getLangOpts().CPlusPlus))
2355  S = S->getParent();
2356  return S;
2357 }
2358 
2359 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2361  switch (Error) {
2362  case ASTContext::GE_None:
2363  return "";
2365  return BuiltinInfo.getHeaderName(ID);
2367  return "stdio.h";
2369  return "setjmp.h";
2371  return "ucontext.h";
2372  }
2373  llvm_unreachable("unhandled error kind");
2374 }
2375 
2377  unsigned ID, SourceLocation Loc) {
2379 
2380  if (getLangOpts().CPlusPlus) {
2381  LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2382  Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2383  CLinkageDecl->setImplicit();
2384  Parent->addDecl(CLinkageDecl);
2385  Parent = CLinkageDecl;
2386  }
2387 
2388  FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2389  /*TInfo=*/nullptr, SC_Extern,
2390  getCurFPFeatures().isFPConstrained(),
2391  false, Type->isFunctionProtoType());
2392  New->setImplicit();
2393  New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2394 
2395  // Create Decl objects for each parameter, adding them to the
2396  // FunctionDecl.
2397  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2399  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2401  Context, New, SourceLocation(), SourceLocation(), nullptr,
2402  FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2403  parm->setScopeInfo(0, i);
2404  Params.push_back(parm);
2405  }
2406  New->setParams(Params);
2407  }
2408 
2409  AddKnownFunctionAttributes(New);
2410  return New;
2411 }
2412 
2413 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2414 /// file scope. lazily create a decl for it. ForRedeclaration is true
2415 /// if we're creating this built-in in anticipation of redeclaring the
2416 /// built-in.
2418  Scope *S, bool ForRedeclaration,
2419  SourceLocation Loc) {
2420  LookupNecessaryTypesForBuiltin(S, ID);
2421 
2423  QualType R = Context.GetBuiltinType(ID, Error);
2424  if (Error) {
2425  if (!ForRedeclaration)
2426  return nullptr;
2427 
2428  // If we have a builtin without an associated type we should not emit a
2429  // warning when we were not able to find a type for it.
2431  Context.BuiltinInfo.allowTypeMismatch(ID))
2432  return nullptr;
2433 
2434  // If we could not find a type for setjmp it is because the jmp_buf type was
2435  // not defined prior to the setjmp declaration.
2437  Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2438  << Context.BuiltinInfo.getName(ID);
2439  return nullptr;
2440  }
2441 
2442  // Generally, we emit a warning that the declaration requires the
2443  // appropriate header.
2444  Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2445  << getHeaderName(Context.BuiltinInfo, ID, Error)
2446  << Context.BuiltinInfo.getName(ID);
2447  return nullptr;
2448  }
2449 
2450  if (!ForRedeclaration &&
2453  Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2454  : diag::ext_implicit_lib_function_decl)
2455  << Context.BuiltinInfo.getName(ID) << R;
2456  if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2457  Diag(Loc, diag::note_include_header_or_declare)
2458  << Header << Context.BuiltinInfo.getName(ID);
2459  }
2460 
2461  if (R.isNull())
2462  return nullptr;
2463 
2464  FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2465  RegisterLocallyScopedExternCDecl(New, S);
2466 
2467  // TUScope is the translation-unit scope to insert this function into.
2468  // FIXME: This is hideous. We need to teach PushOnScopeChains to
2469  // relate Scopes to DeclContexts, and probably eliminate CurContext
2470  // entirely, but we're not there yet.
2471  DeclContext *SavedContext = CurContext;
2472  CurContext = New->getDeclContext();
2473  PushOnScopeChains(New, TUScope);
2474  CurContext = SavedContext;
2475  return New;
2476 }
2477 
2478 /// Typedef declarations don't have linkage, but they still denote the same
2479 /// entity if their types are the same.
2480 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2481 /// isSameEntity.
2485  // This is only interesting when modules are enabled.
2486  if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2487  return;
2488 
2489  // Empty sets are uninteresting.
2490  if (Previous.empty())
2491  return;
2492 
2493  LookupResult::Filter Filter = Previous.makeFilter();
2494  while (Filter.hasNext()) {
2495  NamedDecl *Old = Filter.next();
2496 
2497  // Non-hidden declarations are never ignored.
2498  if (S.isVisible(Old))
2499  continue;
2500 
2501  // Declarations of the same entity are not ignored, even if they have
2502  // different linkages.
2503  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2504  if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2505  Decl->getUnderlyingType()))
2506  continue;
2507 
2508  // If both declarations give a tag declaration a typedef name for linkage
2509  // purposes, then they declare the same entity.
2510  if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2511  Decl->getAnonDeclWithTypedefName())
2512  continue;
2513  }
2514 
2515  Filter.erase();
2516  }
2517 
2518  Filter.done();
2519 }
2520 
2522  QualType OldType;
2523  if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2524  OldType = OldTypedef->getUnderlyingType();
2525  else
2526  OldType = Context.getTypeDeclType(Old);
2527  QualType NewType = New->getUnderlyingType();
2528 
2529  if (NewType->isVariablyModifiedType()) {
2530  // Must not redefine a typedef with a variably-modified type.
2531  int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2532  Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2533  << Kind << NewType;
2534  if (Old->getLocation().isValid())
2535  notePreviousDefinition(Old, New->getLocation());
2536  New->setInvalidDecl();
2537  return true;
2538  }
2539 
2540  if (OldType != NewType &&
2541  !OldType->isDependentType() &&
2542  !NewType->isDependentType() &&
2543  !Context.hasSameType(OldType, NewType)) {
2544  int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2545  Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2546  << Kind << NewType << OldType;
2547  if (Old->getLocation().isValid())
2548  notePreviousDefinition(Old, New->getLocation());
2549  New->setInvalidDecl();
2550  return true;
2551  }
2552  return false;
2553 }
2554 
2555 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2556 /// same name and scope as a previous declaration 'Old'. Figure out
2557 /// how to resolve this situation, merging decls or emitting
2558 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2559 ///
2561  LookupResult &OldDecls) {
2562  // If the new decl is known invalid already, don't bother doing any
2563  // merging checks.
2564  if (New->isInvalidDecl()) return;
2565 
2566  // Allow multiple definitions for ObjC built-in typedefs.
2567  // FIXME: Verify the underlying types are equivalent!
2568  if (getLangOpts().ObjC) {
2569  const IdentifierInfo *TypeID = New->getIdentifier();
2570  switch (TypeID->getLength()) {
2571  default: break;
2572  case 2:
2573  {
2574  if (!TypeID->isStr("id"))
2575  break;
2576  QualType T = New->getUnderlyingType();
2577  if (!T->isPointerType())
2578  break;
2579  if (!T->isVoidPointerType()) {
2580  QualType PT = T->castAs<PointerType>()->getPointeeType();
2581  if (!PT->isStructureType())
2582  break;
2583  }
2584  Context.setObjCIdRedefinitionType(T);
2585  // Install the built-in type for 'id', ignoring the current definition.
2586  New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2587  return;
2588  }
2589  case 5:
2590  if (!TypeID->isStr("Class"))
2591  break;
2593  // Install the built-in type for 'Class', ignoring the current definition.
2594  New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2595  return;
2596  case 3:
2597  if (!TypeID->isStr("SEL"))
2598  break;
2600  // Install the built-in type for 'SEL', ignoring the current definition.
2601  New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2602  return;
2603  }
2604  // Fall through - the typedef name was not a builtin type.
2605  }
2606 
2607  // Verify the old decl was also a type.
2608  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2609  if (!Old) {
2610  Diag(New->getLocation(), diag::err_redefinition_different_kind)
2611  << New->getDeclName();
2612 
2613  NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2614  if (OldD->getLocation().isValid())
2615  notePreviousDefinition(OldD, New->getLocation());
2616 
2617  return New->setInvalidDecl();
2618  }
2619 
2620  // If the old declaration is invalid, just give up here.
2621  if (Old->isInvalidDecl())
2622  return New->setInvalidDecl();
2623 
2624  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2625  auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2626  auto *NewTag = New->getAnonDeclWithTypedefName();
2627  NamedDecl *Hidden = nullptr;
2628  if (OldTag && NewTag &&
2629  OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2630  !hasVisibleDefinition(OldTag, &Hidden)) {
2631  // There is a definition of this tag, but it is not visible. Use it
2632  // instead of our tag.
2633  New->setTypeForDecl(OldTD->getTypeForDecl());
2634  if (OldTD->isModed())
2635  New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2636  OldTD->getUnderlyingType());
2637  else
2638  New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2639 
2640  // Make the old tag definition visible.
2641  makeMergedDefinitionVisible(Hidden);
2642 
2643  // If this was an unscoped enumeration, yank all of its enumerators
2644  // out of the scope.
2645  if (isa<EnumDecl>(NewTag)) {
2646  Scope *EnumScope = getNonFieldDeclScope(S);
2647  for (auto *D : NewTag->decls()) {
2648  auto *ED = cast<EnumConstantDecl>(D);
2649  assert(EnumScope->isDeclScope(ED));
2650  EnumScope->RemoveDecl(ED);
2651  IdResolver.RemoveDecl(ED);
2652  ED->getLexicalDeclContext()->removeDecl(ED);
2653  }
2654  }
2655  }
2656  }
2657 
2658  // If the typedef types are not identical, reject them in all languages and
2659  // with any extensions enabled.
2660  if (isIncompatibleTypedef(Old, New))
2661  return;
2662 
2663  // The types match. Link up the redeclaration chain and merge attributes if
2664  // the old declaration was a typedef.
2665  if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2666  New->setPreviousDecl(Typedef);
2667  mergeDeclAttributes(New, Old);
2668  }
2669 
2670  if (getLangOpts().MicrosoftExt)
2671  return;
2672 
2673  if (getLangOpts().CPlusPlus) {
2674  // C++ [dcl.typedef]p2:
2675  // In a given non-class scope, a typedef specifier can be used to
2676  // redefine the name of any type declared in that scope to refer
2677  // to the type to which it already refers.
2678  if (!isa<CXXRecordDecl>(CurContext))
2679  return;
2680 
2681  // C++0x [dcl.typedef]p4:
2682  // In a given class scope, a typedef specifier can be used to redefine
2683  // any class-name declared in that scope that is not also a typedef-name
2684  // to refer to the type to which it already refers.
2685  //
2686  // This wording came in via DR424, which was a correction to the
2687  // wording in DR56, which accidentally banned code like:
2688  //
2689  // struct S {
2690  // typedef struct A { } A;
2691  // };
2692  //
2693  // in the C++03 standard. We implement the C++0x semantics, which
2694  // allow the above but disallow
2695  //
2696  // struct S {
2697  // typedef int I;
2698  // typedef int I;
2699  // };
2700  //
2701  // since that was the intent of DR56.
2702  if (!isa<TypedefNameDecl>(Old))
2703  return;
2704 
2705  Diag(New->getLocation(), diag::err_redefinition)
2706  << New->getDeclName();
2707  notePreviousDefinition(Old, New->getLocation());
2708  return New->setInvalidDecl();
2709  }
2710 
2711  // Modules always permit redefinition of typedefs, as does C11.
2712  if (getLangOpts().Modules || getLangOpts().C11)
2713  return;
2714 
2715  // If we have a redefinition of a typedef in C, emit a warning. This warning
2716  // is normally mapped to an error, but can be controlled with
2717  // -Wtypedef-redefinition. If either the original or the redefinition is
2718  // in a system header, don't emit this for compatibility with GCC.
2719  if (getDiagnostics().getSuppressSystemWarnings() &&
2720  // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2721  (Old->isImplicit() ||
2722  Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2723  Context.getSourceManager().isInSystemHeader(New->getLocation())))
2724  return;
2725 
2726  Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2727  << New->getDeclName();
2728  notePreviousDefinition(Old, New->getLocation());
2729 }
2730 
2731 /// DeclhasAttr - returns true if decl Declaration already has the target
2732 /// attribute.
2733 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2734  const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2735  const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2736  for (const auto *i : D->attrs())
2737  if (i->getKind() == A->getKind()) {
2738  if (Ann) {
2739  if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2740  return true;
2741  continue;
2742  }
2743  // FIXME: Don't hardcode this check
2744  if (OA && isa<OwnershipAttr>(i))
2745  return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2746  return true;
2747  }
2748 
2749  return false;
2750 }
2751 
2753  if (VarDecl *VD = dyn_cast<VarDecl>(D))
2754  return VD->isThisDeclarationADefinition();
2755  if (TagDecl *TD = dyn_cast<TagDecl>(D))
2756  return TD->isCompleteDefinition() || TD->isBeingDefined();
2757  return true;
2758 }
2759 
2760 /// Merge alignment attributes from \p Old to \p New, taking into account the
2761 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2762 ///
2763 /// \return \c true if any attributes were added to \p New.
2764 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2765  // Look for alignas attributes on Old, and pick out whichever attribute
2766  // specifies the strictest alignment requirement.
2767  AlignedAttr *OldAlignasAttr = nullptr;
2768  AlignedAttr *OldStrictestAlignAttr = nullptr;
2769  unsigned OldAlign = 0;
2770  for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2771  // FIXME: We have no way of representing inherited dependent alignments
2772  // in a case like:
2773  // template<int A, int B> struct alignas(A) X;
2774  // template<int A, int B> struct alignas(B) X {};
2775  // For now, we just ignore any alignas attributes which are not on the
2776  // definition in such a case.
2777  if (I->isAlignmentDependent())
2778  return false;
2779 
2780  if (I->isAlignas())
2781  OldAlignasAttr = I;
2782 
2783  unsigned Align = I->getAlignment(S.Context);
2784  if (Align > OldAlign) {
2785  OldAlign = Align;
2786  OldStrictestAlignAttr = I;
2787  }
2788  }
2789 
2790  // Look for alignas attributes on New.
2791  AlignedAttr *NewAlignasAttr = nullptr;
2792  unsigned NewAlign = 0;
2793  for (auto *I : New->specific_attrs<AlignedAttr>()) {
2794  if (I->isAlignmentDependent())
2795  return false;
2796 
2797  if (I->isAlignas())
2798  NewAlignasAttr = I;
2799 
2800  unsigned Align = I->getAlignment(S.Context);
2801  if (Align > NewAlign)
2802  NewAlign = Align;
2803  }
2804 
2805  if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2806  // Both declarations have 'alignas' attributes. We require them to match.
2807  // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2808  // fall short. (If two declarations both have alignas, they must both match
2809  // every definition, and so must match each other if there is a definition.)
2810 
2811  // If either declaration only contains 'alignas(0)' specifiers, then it
2812  // specifies the natural alignment for the type.
2813  if (OldAlign == 0 || NewAlign == 0) {
2814  QualType Ty;
2815  if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2816  Ty = VD->getType();
2817  else
2818  Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2819 
2820  if (OldAlign == 0)
2821  OldAlign = S.Context.getTypeAlign(Ty);
2822  if (NewAlign == 0)
2823  NewAlign = S.Context.getTypeAlign(Ty);
2824  }
2825 
2826  if (OldAlign != NewAlign) {
2827  S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2829  << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2830  S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2831  }
2832  }
2833 
2834  if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2835  // C++11 [dcl.align]p6:
2836  // if any declaration of an entity has an alignment-specifier,
2837  // every defining declaration of that entity shall specify an
2838  // equivalent alignment.
2839  // C11 6.7.5/7:
2840  // If the definition of an object does not have an alignment
2841  // specifier, any other declaration of that object shall also
2842  // have no alignment specifier.
2843  S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2844  << OldAlignasAttr;
2845  S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2846  << OldAlignasAttr;
2847  }
2848 
2849  bool AnyAdded = false;
2850 
2851  // Ensure we have an attribute representing the strictest alignment.
2852  if (OldAlign > NewAlign) {
2853  AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2854  Clone->setInherited(true);
2855  New->addAttr(Clone);
2856  AnyAdded = true;
2857  }
2858 
2859  // Ensure we have an alignas attribute if the old declaration had one.
2860  if (OldAlignasAttr && !NewAlignasAttr &&
2861  !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2862  AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2863  Clone->setInherited(true);
2864  New->addAttr(Clone);
2865  AnyAdded = true;
2866  }
2867 
2868  return AnyAdded;
2869 }
2870 
2871 #define WANT_DECL_MERGE_LOGIC
2872 #include "clang/Sema/AttrParsedAttrImpl.inc"
2873 #undef WANT_DECL_MERGE_LOGIC
2874 
2875 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2876  const InheritableAttr *Attr,
2878  // Diagnose any mutual exclusions between the attribute that we want to add
2879  // and attributes that already exist on the declaration.
2880  if (!DiagnoseMutualExclusions(S, D, Attr))
2881  return false;
2882 
2883  // This function copies an attribute Attr from a previous declaration to the
2884  // new declaration D if the new declaration doesn't itself have that attribute
2885  // yet or if that attribute allows duplicates.
2886  // If you're adding a new attribute that requires logic different from
2887  // "use explicit attribute on decl if present, else use attribute from
2888  // previous decl", for example if the attribute needs to be consistent
2889  // between redeclarations, you need to call a custom merge function here.
2890  InheritableAttr *NewAttr = nullptr;
2891  if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2892  NewAttr = S.mergeAvailabilityAttr(
2893  D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2894  AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2895  AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2896  AA->getPriority());
2897  else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2898  NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2899  else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2900  NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2901  else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2902  NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2903  else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2904  NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2905  else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2906  NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2907  else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2908  NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2909  FA->getFirstArg());
2910  else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2911  NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2912  else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2913  NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2914  else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2915  NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2916  IA->getInheritanceModel());
2917  else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2918  NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2919  &S.Context.Idents.get(AA->getSpelling()));
2920  else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2921  (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2922  isa<CUDAGlobalAttr>(Attr))) {
2923  // CUDA target attributes are part of function signature for
2924  // overloading purposes and must not be merged.
2925  return false;
2926  } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2927  NewAttr = S.mergeMinSizeAttr(D, *MA);
2928  else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2929  NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2930  else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2931  NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2932  else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2933  NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2934  else if (isa<AlignedAttr>(Attr))
2935  // AlignedAttrs are handled separately, because we need to handle all
2936  // such attributes on a declaration at the same time.
2937  NewAttr = nullptr;
2938  else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2939  (AMK == Sema::AMK_Override ||
2942  NewAttr = nullptr;
2943  else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2944  NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2945  else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2946  NewAttr = S.mergeImportModuleAttr(D, *IMA);
2947  else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2948  NewAttr = S.mergeImportNameAttr(D, *INA);
2949  else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2950  NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2951  else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2952  NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2953  else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2954  NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2955  else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2956  NewAttr =
2957  S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2958  else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2959  NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2960  else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2961  NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2962 
2963  if (NewAttr) {
2964  NewAttr->setInherited(true);
2965  D->addAttr(NewAttr);
2966  if (isa<MSInheritanceAttr>(NewAttr))
2967  S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2968  return true;
2969  }
2970 
2971  return false;
2972 }
2973 
2974 static const NamedDecl *getDefinition(const Decl *D) {
2975  if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2976  return TD->getDefinition();
2977  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2978  const VarDecl *Def = VD->getDefinition();
2979  if (Def)
2980  return Def;
2981  return VD->getActingDefinition();
2982  }
2983  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2984  const FunctionDecl *Def = nullptr;
2985  if (FD->isDefined(Def, true))
2986  return Def;
2987  }
2988  return nullptr;
2989 }
2990 
2991 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2992  for (const auto *Attribute : D->attrs())
2993  if (Attribute->getKind() == Kind)
2994  return true;
2995  return false;
2996 }
2997 
2998 /// checkNewAttributesAfterDef - If we already have a definition, check that
2999 /// there are no new attributes in this declaration.
3000 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3001  if (!New->hasAttrs())
3002  return;
3003 
3004  const NamedDecl *Def = getDefinition(Old);
3005  if (!Def || Def == New)
3006  return;
3007 
3008  AttrVec &NewAttributes = New->getAttrs();
3009  for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3010  const Attr *NewAttribute = NewAttributes[I];
3011 
3012  if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3013  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3014  Sema::SkipBodyInfo SkipBody;
3015  S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3016 
3017  // If we're skipping this definition, drop the "alias" attribute.
3018  if (SkipBody.ShouldSkip) {
3019  NewAttributes.erase(NewAttributes.begin() + I);
3020  --E;
3021  continue;
3022  }
3023  } else {
3024  VarDecl *VD = cast<VarDecl>(New);
3025  unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3027  ? diag::err_alias_after_tentative
3028  : diag::err_redefinition;
3029  S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3030  if (Diag == diag::err_redefinition)
3031  S.notePreviousDefinition(Def, VD->getLocation());
3032  else
3033  S.Diag(Def->getLocation(), diag::note_previous_definition);
3034  VD->setInvalidDecl();
3035  }
3036  ++I;
3037  continue;
3038  }
3039 
3040  if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3041  // Tentative definitions are only interesting for the alias check above.
3042  if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3043  ++I;
3044  continue;
3045  }
3046  }
3047 
3048  if (hasAttribute(Def, NewAttribute->getKind())) {
3049  ++I;
3050  continue; // regular attr merging will take care of validating this.
3051  }
3052 
3053  if (isa<C11NoReturnAttr>(NewAttribute)) {
3054  // C's _Noreturn is allowed to be added to a function after it is defined.
3055  ++I;
3056  continue;
3057  } else if (isa<UuidAttr>(NewAttribute)) {
3058  // msvc will allow a subsequent definition to add an uuid to a class
3059  ++I;
3060  continue;
3061  } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3062  if (AA->isAlignas()) {
3063  // C++11 [dcl.align]p6:
3064  // if any declaration of an entity has an alignment-specifier,
3065  // every defining declaration of that entity shall specify an
3066  // equivalent alignment.
3067  // C11 6.7.5/7:
3068  // If the definition of an object does not have an alignment
3069  // specifier, any other declaration of that object shall also
3070  // have no alignment specifier.
3071  S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3072  << AA;
3073  S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3074  << AA;
3075  NewAttributes.erase(NewAttributes.begin() + I);
3076  --E;
3077  continue;
3078  }
3079  } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3080  // If there is a C definition followed by a redeclaration with this
3081  // attribute then there are two different definitions. In C++, prefer the
3082  // standard diagnostics.
3083  if (!S.getLangOpts().CPlusPlus) {
3084  S.Diag(NewAttribute->getLocation(),
3085  diag::err_loader_uninitialized_redeclaration);
3086  S.Diag(Def->getLocation(), diag::note_previous_definition);
3087  NewAttributes.erase(NewAttributes.begin() + I);
3088  --E;
3089  continue;
3090  }
3091  } else if (isa<SelectAnyAttr>(NewAttribute) &&
3092  cast<VarDecl>(New)->isInline() &&
3093  !cast<VarDecl>(New)->isInlineSpecified()) {
3094  // Don't warn about applying selectany to implicitly inline variables.
3095  // Older compilers and language modes would require the use of selectany
3096  // to make such variables inline, and it would have no effect if we
3097  // honored it.
3098  ++I;
3099  continue;
3100  } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3101  // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3102  // declarations after definitions.
3103  ++I;
3104  continue;
3105  }
3106 
3107  S.Diag(NewAttribute->getLocation(),
3108  diag::warn_attribute_precede_definition);
3109  S.Diag(Def->getLocation(), diag::note_previous_definition);
3110  NewAttributes.erase(NewAttributes.begin() + I);
3111  --E;
3112  }
3113 }
3114 
3115 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3116  const ConstInitAttr *CIAttr,
3117  bool AttrBeforeInit) {
3118  SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3119 
3120  // Figure out a good way to write this specifier on the old declaration.
3121  // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3122  // enough of the attribute list spelling information to extract that without
3123  // heroics.
3124  std::string SuitableSpelling;
3125  if (S.getLangOpts().CPlusPlus20)
3126  SuitableSpelling = std::string(
3127  S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3128  if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3129  SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3130  InsertLoc, {tok::l_square, tok::l_square,
3131  S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3132  S.PP.getIdentifierInfo("require_constant_initialization"),
3133  tok::r_square, tok::r_square}));
3134  if (SuitableSpelling.empty())
3135  SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3136  InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3137  S.PP.getIdentifierInfo("require_constant_initialization"),
3138  tok::r_paren, tok::r_paren}));
3139  if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3140  SuitableSpelling = "constinit";
3141  if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3142  SuitableSpelling = "[[clang::require_constant_initialization]]";
3143  if (SuitableSpelling.empty())
3144  SuitableSpelling = "__attribute__((require_constant_initialization))";
3145  SuitableSpelling += " ";
3146 
3147  if (AttrBeforeInit) {
3148  // extern constinit int a;
3149  // int a = 0; // error (missing 'constinit'), accepted as extension
3150  assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3151  S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3152  << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3153  S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3154  } else {
3155  // int a = 0;
3156  // constinit extern int a; // error (missing 'constinit')
3157  S.Diag(CIAttr->getLocation(),
3158  CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3159  : diag::warn_require_const_init_added_too_late)
3160  << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3161  S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3162  << CIAttr->isConstinit()
3163  << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3164  }
3165 }
3166 
3167 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3169  AvailabilityMergeKind AMK) {
3170  if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3171  UsedAttr *NewAttr = OldAttr->clone(Context);
3172  NewAttr->setInherited(true);
3173  New->addAttr(NewAttr);
3174  }
3175  if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3176  RetainAttr *NewAttr = OldAttr->clone(Context);
3177  NewAttr->setInherited(true);
3178  New->addAttr(NewAttr);
3179  }
3180 
3181  if (!Old->hasAttrs() && !New->hasAttrs())
3182  return;
3183 
3184  // [dcl.constinit]p1:
3185  // If the [constinit] specifier is applied to any declaration of a
3186  // variable, it shall be applied to the initializing declaration.
3187  const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3188  const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3189  if (bool(OldConstInit) != bool(NewConstInit)) {
3190  const auto *OldVD = cast<VarDecl>(Old);
3191  auto *NewVD = cast<VarDecl>(New);
3192 
3193  // Find the initializing declaration. Note that we might not have linked
3194  // the new declaration into the redeclaration chain yet.
3195  const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3196  if (!InitDecl &&
3197  (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3198  InitDecl = NewVD;
3199 
3200  if (InitDecl == NewVD) {
3201  // This is the initializing declaration. If it would inherit 'constinit',
3202  // that's ill-formed. (Note that we do not apply this to the attribute
3203  // form).
3204  if (OldConstInit && OldConstInit->isConstinit())
3205  diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3206  /*AttrBeforeInit=*/true);
3207  } else if (NewConstInit) {
3208  // This is the first time we've been told that this declaration should
3209  // have a constant initializer. If we already saw the initializing
3210  // declaration, this is too late.
3211  if (InitDecl && InitDecl != NewVD) {
3212  diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3213  /*AttrBeforeInit=*/false);
3214  NewVD->dropAttr<ConstInitAttr>();
3215  }
3216  }
3217  }
3218 
3219  // Attributes declared post-definition are currently ignored.
3220  checkNewAttributesAfterDef(*this, New, Old);
3221 
3222  if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3223  if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3224  if (!OldA->isEquivalent(NewA)) {
3225  // This redeclaration changes __asm__ label.
3226  Diag(New->getLocation(), diag::err_different_asm_label);
3227  Diag(OldA->getLocation(), diag::note_previous_declaration);
3228  }
3229  } else if (Old->isUsed()) {
3230  // This redeclaration adds an __asm__ label to a declaration that has
3231  // already been ODR-used.
3232  Diag(New->getLocation(), diag::err_late_asm_label_name)
3233  << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3234  }
3235  }
3236 
3237  // Re-declaration cannot add abi_tag's.
3238  if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3239  if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3240  for (const auto &NewTag : NewAbiTagAttr->tags()) {
3241  if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3242  Diag(NewAbiTagAttr->getLocation(),
3243  diag::err_new_abi_tag_on_redeclaration)
3244  << NewTag;
3245  Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3246  }
3247  }
3248  } else {
3249  Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3250  Diag(Old->getLocation(), diag::note_previous_declaration);
3251  }
3252  }
3253 
3254  // This redeclaration adds a section attribute.
3255  if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3256  if (auto *VD = dyn_cast<VarDecl>(New)) {
3257  if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3258  Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3259  Diag(Old->getLocation(), diag::note_previous_declaration);
3260  }
3261  }
3262  }
3263 
3264  // Redeclaration adds code-seg attribute.
3265  const auto *NewCSA = New->getAttr<CodeSegAttr>();
3266  if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3267  !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3268  Diag(New->getLocation(), diag::warn_mismatched_section)
3269  << 0 /*codeseg*/;
3270  Diag(Old->getLocation(), diag::note_previous_declaration);
3271  }
3272 
3273  if (!Old->hasAttrs())
3274  return;
3275 
3276  bool foundAny = New->hasAttrs();
3277 
3278  // Ensure that any moving of objects within the allocated map is done before
3279  // we process them.
3280  if (!foundAny) New->setAttrs(AttrVec());
3281 
3282  for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3283  // Ignore deprecated/unavailable/availability attributes if requested.
3284  AvailabilityMergeKind LocalAMK = AMK_None;
3285  if (isa<DeprecatedAttr>(I) ||
3286  isa<UnavailableAttr>(I) ||
3287  isa<AvailabilityAttr>(I)) {
3288  switch (AMK) {
3289  case AMK_None:
3290  continue;
3291 
3292  case AMK_Redeclaration:
3293  case AMK_Override:
3294  case AMK_ProtocolImplementation:
3295  case AMK_OptionalProtocolImplementation:
3296  LocalAMK = AMK;
3297  break;
3298  }
3299  }
3300 
3301  // Already handled.
3302  if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3303  continue;
3304 
3305  if (mergeDeclAttribute(*this, New, I, LocalAMK))
3306  foundAny = true;
3307  }
3308 
3309  if (mergeAlignedAttrs(*this, New, Old))
3310  foundAny = true;
3311 
3312  if (!foundAny) New->dropAttrs();
3313 }
3314 
3315 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3316 /// to the new one.
3318  const ParmVarDecl *oldDecl,
3319  Sema &S) {
3320  // C++11 [dcl.attr.depend]p2:
3321  // The first declaration of a function shall specify the
3322  // carries_dependency attribute for its declarator-id if any declaration
3323  // of the function specifies the carries_dependency attribute.
3324  const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3325  if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3326  S.Diag(CDA->getLocation(),
3327  diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3328  // Find the first declaration of the parameter.
3329  // FIXME: Should we build redeclaration chains for function parameters?
3330  const FunctionDecl *FirstFD =
3331  cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3332  const ParmVarDecl *FirstVD =
3333  FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3334  S.Diag(FirstVD->getLocation(),
3335  diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3336  }
3337 
3338  if (!oldDecl->hasAttrs())
3339  return;
3340 
3341  bool foundAny = newDecl->hasAttrs();
3342 
3343  // Ensure that any moving of objects within the allocated map is
3344  // done before we process them.
3345  if (!foundAny) newDecl->setAttrs(AttrVec());
3346 
3347  for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3348  if (!DeclHasAttr(newDecl, I)) {
3349  InheritableAttr *newAttr =
3350  cast<InheritableParamAttr>(I->clone(S.Context));
3351  newAttr->setInherited(true);
3352  newDecl->addAttr(newAttr);
3353  foundAny = true;
3354  }
3355  }
3356 
3357  if (!foundAny) newDecl->dropAttrs();
3358 }
3359 
3361  const ASTContext &Ctx) {
3362 
3363  auto NoSizeInfo = [&Ctx](QualType Ty) {
3364  if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3365  return true;
3366  if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3367  return VAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star;
3368  return false;
3369  };
3370 
3371  // `type[]` is equivalent to `type *` and `type[*]`.
3372  if (NoSizeInfo(Old) && NoSizeInfo(New))
3373  return true;
3374 
3375  // Don't try to compare VLA sizes, unless one of them has the star modifier.
3376  if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3377  const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3378  const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3379  if ((OldVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star) ^
3380  (NewVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star))
3381  return false;
3382  return true;
3383  }
3384 
3385  // Only compare size, ignore Size modifiers and CVR.
3386  if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3387  return Ctx.getAsConstantArrayType(Old)->getSize() ==
3388  Ctx.getAsConstantArrayType(New)->getSize();
3389  }
3390 
3391  // Don't try to compare dependent sized array
3393  return true;
3394  }
3395 
3396  return Old == New;
3397 }
3398 
3399 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3400  const ParmVarDecl *OldParam,
3401  Sema &S) {
3402  if (auto Oldnullability = OldParam->getType()->getNullability()) {
3403  if (auto Newnullability = NewParam->getType()->getNullability()) {
3404  if (*Oldnullability != *Newnullability) {
3405  S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3407  *Newnullability,
3409  != 0))
3411  *Oldnullability,
3413  != 0));
3414  S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3415  }
3416  } else {
3417  QualType NewT = NewParam->getType();
3418  NewT = S.Context.getAttributedType(
3419  AttributedType::getNullabilityAttrKind(*Oldnullability),
3420  NewT, NewT);
3421  NewParam->setType(NewT);
3422  }
3423  }
3424  const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3425  const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3426  if (OldParamDT && NewParamDT &&
3427  OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3428  QualType OldParamOT = OldParamDT->getOriginalType();
3429  QualType NewParamOT = NewParamDT->getOriginalType();
3430  if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3431  S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3432  << NewParam << NewParamOT;
3433  S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3434  << OldParamOT;
3435  }
3436  }
3437 }
3438 
3439 namespace {
3440 
3441 /// Used in MergeFunctionDecl to keep track of function parameters in
3442 /// C.
3443 struct GNUCompatibleParamWarning {
3444  ParmVarDecl *OldParm;
3445  ParmVarDecl *NewParm;
3446  QualType PromotedType;
3447 };
3448 
3449 } // end anonymous namespace
3450 
3451 // Determine whether the previous declaration was a definition, implicit
3452 // declaration, or a declaration.
3453 template <typename T>
3454 static std::pair<diag::kind, SourceLocation>
3455 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3456  diag::kind PrevDiag;
3457  SourceLocation OldLocation = Old->getLocation();
3458  if (Old->isThisDeclarationADefinition())
3459  PrevDiag = diag::note_previous_definition;
3460  else if (Old->isImplicit()) {
3461  PrevDiag = diag::note_previous_implicit_declaration;
3462  if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3463  if (FD->getBuiltinID())
3464  PrevDiag = diag::note_previous_builtin_declaration;
3465  }
3466  if (OldLocation.isInvalid())
3467  OldLocation = New->getLocation();
3468  } else
3469  PrevDiag = diag::note_previous_declaration;
3470  return std::make_pair(PrevDiag, OldLocation);
3471 }
3472 
3473 /// canRedefineFunction - checks if a function can be redefined. Currently,
3474 /// only extern inline functions can be redefined, and even then only in
3475 /// GNU89 mode.
3476 static bool canRedefineFunction(const FunctionDecl *FD,
3477  const LangOptions& LangOpts) {
3478  return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3479  !LangOpts.CPlusPlus &&
3480  FD->isInlineSpecified() &&
3481  FD->getStorageClass() == SC_Extern);
3482 }
3483 
3485  const AttributedType *AT = T->getAs<AttributedType>();
3486  while (AT && !AT->isCallingConv())
3487  AT = AT->getModifiedType()->getAs<AttributedType>();
3488  return AT;
3489 }
3490 
3491 template <typename T>
3492 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3493  const DeclContext *DC = Old->getDeclContext();
3494  if (DC->isRecord())
3495  return false;
3496 
3497  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3498  if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3499  return true;
3500  if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3501  return true;
3502  return false;
3503 }
3504 
3505 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3506 static bool isExternC(VarTemplateDecl *) { return false; }
3507 static bool isExternC(FunctionTemplateDecl *) { return false; }
3508 
3509 /// Check whether a redeclaration of an entity introduced by a
3510 /// using-declaration is valid, given that we know it's not an overload
3511 /// (nor a hidden tag declaration).
3512 template<typename ExpectedDecl>
3514  ExpectedDecl *New) {
3515  // C++11 [basic.scope.declarative]p4:
3516  // Given a set of declarations in a single declarative region, each of
3517  // which specifies the same unqualified name,
3518  // -- they shall all refer to the same entity, or all refer to functions
3519  // and function templates; or
3520  // -- exactly one declaration shall declare a class name or enumeration
3521  // name that is not a typedef name and the other declarations shall all
3522  // refer to the same variable or enumerator, or all refer to functions
3523  // and function templates; in this case the class name or enumeration
3524  // name is hidden (3.3.10).
3525 
3526  // C++11 [namespace.udecl]p14:
3527  // If a function declaration in namespace scope or block scope has the
3528  // same name and the same parameter-type-list as a function introduced
3529  // by a using-declaration, and the declarations do not declare the same
3530  // function, the program is ill-formed.
3531 
3532  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3533  if (Old &&
3534  !Old->getDeclContext()->getRedeclContext()->Equals(
3535  New->getDeclContext()->getRedeclContext()) &&
3536  !(isExternC(Old) && isExternC(New)))
3537  Old = nullptr;
3538 
3539  if (!Old) {
3540  S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3541  S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3542  S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3543  return true;
3544  }
3545  return false;
3546 }
3547 
3549  const FunctionDecl *B) {
3550  assert(A->getNumParams() == B->getNumParams());
3551 
3552  auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3553  const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3554  const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3555  if (AttrA == AttrB)
3556  return true;
3557  return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3558  AttrA->isDynamic() == AttrB->isDynamic();
3559  };
3560 
3561  return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3562 }
3563 
3564 /// If necessary, adjust the semantic declaration context for a qualified
3565 /// declaration to name the correct inline namespace within the qualifier.
3567  DeclaratorDecl *OldD) {
3568  // The only case where we need to update the DeclContext is when
3569  // redeclaration lookup for a qualified name finds a declaration
3570  // in an inline namespace within the context named by the qualifier:
3571  //
3572  // inline namespace N { int f(); }
3573  // int ::f(); // Sema DC needs adjusting from :: to N::.
3574  //
3575  // For unqualified declarations, the semantic context *can* change
3576  // along the redeclaration chain (for local extern declarations,
3577  // extern "C" declarations, and friend declarations in particular).
3578  if (!NewD->getQualifier())
3579  return;
3580 
3581  // NewD is probably already in the right context.
3582  auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3583  auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3584  if (NamedDC->Equals(SemaDC))
3585  return;
3586 
3587  assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3588  NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3589  "unexpected context for redeclaration");
3590 
3591  auto *LexDC = NewD->getLexicalDeclContext();
3592  auto FixSemaDC = [=](NamedDecl *D) {
3593  if (!D)
3594  return;
3595  D->setDeclContext(SemaDC);
3596  D->setLexicalDeclContext(LexDC);
3597  };
3598 
3599  FixSemaDC(NewD);
3600  if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3601  FixSemaDC(FD->getDescribedFunctionTemplate());
3602  else if (auto *VD = dyn_cast<VarDecl>(NewD))
3603  FixSemaDC(VD->getDescribedVarTemplate());
3604 }
3605 
3606 /// MergeFunctionDecl - We just parsed a function 'New' from
3607 /// declarator D which has the same name and scope as a previous
3608 /// declaration 'Old'. Figure out how to resolve this situation,
3609 /// merging decls or emitting diagnostics as appropriate.
3610 ///
3611 /// In C++, New and Old must be declarations that are not
3612 /// overloaded. Use IsOverload to determine whether New and Old are
3613 /// overloaded, and to select the Old declaration that New should be
3614 /// merged with.
3615 ///
3616 /// Returns true if there was an error, false otherwise.
3618  bool MergeTypeWithOld, bool NewDeclIsDefn) {
3619  // Verify the old decl was also a function.
3620  FunctionDecl *Old = OldD->getAsFunction();
3621  if (!Old) {
3622  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3623  if (New->getFriendObjectKind()) {
3624  Diag(New->getLocation(), diag::err_using_decl_friend);
3625  Diag(Shadow->getTargetDecl()->getLocation(),
3626  diag::note_using_decl_target);
3627  Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3628  << 0;
3629  return true;
3630  }
3631 
3632  // Check whether the two declarations might declare the same function or
3633  // function template.
3634  if (FunctionTemplateDecl *NewTemplate =
3636  if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3637  NewTemplate))
3638  return true;
3639  OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3640  ->getAsFunction();
3641  } else {
3642  if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3643  return true;
3644  OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3645  }
3646  } else {
3647  Diag(New->getLocation(), diag::err_redefinition_different_kind)
3648  << New->getDeclName();
3649  notePreviousDefinition(OldD, New->getLocation());
3650  return true;
3651  }
3652  }
3653 
3654  // If the old declaration was found in an inline namespace and the new
3655  // declaration was qualified, update the DeclContext to match.
3657 
3658  // If the old declaration is invalid, just give up here.
3659  if (Old->isInvalidDecl())
3660  return true;
3661 
3662  // Disallow redeclaration of some builtins.
3663  if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3664  Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3665  Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3666  << Old << Old->getType();
3667  return true;
3668  }
3669 
3670  diag::kind PrevDiag;
3671  SourceLocation OldLocation;
3672  std::tie(PrevDiag, OldLocation) =
3674 
3675  // Don't complain about this if we're in GNU89 mode and the old function
3676  // is an extern inline function.
3677  // Don't complain about specializations. They are not supposed to have
3678  // storage classes.
3679  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3680  New->getStorageClass() == SC_Static &&
3681  Old->hasExternalFormalLinkage() &&
3683  !canRedefineFunction(Old, getLangOpts())) {
3684  if (getLangOpts().MicrosoftExt) {
3685  Diag(New->getLocation(), diag::ext_static_non_static) << New;
3686  Diag(OldLocation, PrevDiag);
3687  } else {
3688  Diag(New->getLocation(), diag::err_static_non_static) << New;
3689  Diag(OldLocation, PrevDiag);
3690  return true;
3691  }
3692  }
3693 
3694  if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3695  if (!Old->hasAttr<InternalLinkageAttr>()) {
3696  Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3697  << ILA;
3698  Diag(Old->getLocation(), diag::note_previous_declaration);
3699  New->dropAttr<InternalLinkageAttr>();
3700  }
3701 
3702  if (auto *EA = New->getAttr<ErrorAttr>()) {
3703  if (!Old->hasAttr<ErrorAttr>()) {
3704  Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3705  Diag(Old->getLocation(), diag::note_previous_declaration);
3706  New->dropAttr<ErrorAttr>();
3707  }
3708  }
3709 
3710  if (CheckRedeclarationInModule(New, Old))
3711  return true;
3712 
3713  if (!getLangOpts().CPlusPlus) {
3714  bool OldOvl = Old->hasAttr<OverloadableAttr>();
3715  if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3716  Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3717  << New << OldOvl;
3718 
3719  // Try our best to find a decl that actually has the overloadable
3720  // attribute for the note. In most cases (e.g. programs with only one
3721  // broken declaration/definition), this won't matter.
3722  //
3723  // FIXME: We could do this if we juggled some extra state in
3724  // OverloadableAttr, rather than just removing it.
3725  const Decl *DiagOld = Old;
3726  if (OldOvl) {
3727  auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3728  const auto *A = D->getAttr<OverloadableAttr>();
3729  return A && !A->isImplicit();
3730  });
3731  // If we've implicitly added *all* of the overloadable attrs to this
3732  // chain, emitting a "previous redecl" note is pointless.
3733  DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3734  }
3735 
3736  if (DiagOld)
3737  Diag(DiagOld->getLocation(),
3738  diag::note_attribute_overloadable_prev_overload)
3739  << OldOvl;
3740 
3741  if (OldOvl)
3742  New->addAttr(OverloadableAttr::CreateImplicit(Context));
3743  else
3744  New->dropAttr<OverloadableAttr>();
3745  }
3746  }
3747 
3748  // If a function is first declared with a calling convention, but is later
3749  // declared or defined without one, all following decls assume the calling
3750  // convention of the first.
3751  //
3752  // It's OK if a function is first declared without a calling convention,
3753  // but is later declared or defined with the default calling convention.
3754  //
3755  // To test if either decl has an explicit calling convention, we look for
3756  // AttributedType sugar nodes on the type as written. If they are missing or
3757  // were canonicalized away, we assume the calling convention was implicit.
3758  //
3759  // Note also that we DO NOT return at this point, because we still have
3760  // other tests to run.
3761  QualType OldQType = Context.getCanonicalType(Old->getType());
3762  QualType NewQType = Context.getCanonicalType(New->getType());
3763  const FunctionType *OldType = cast<FunctionType>(OldQType);
3764  const FunctionType *NewType = cast<FunctionType>(NewQType);
3765  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3766  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3767  bool RequiresAdjustment = false;
3768 
3769  if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3770  FunctionDecl *First = Old->getFirstDecl();
3771  const FunctionType *FT =
3772  First->getType().getCanonicalType()->castAs<FunctionType>();
3773  FunctionType::ExtInfo FI = FT->getExtInfo();
3774  bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3775  if (!NewCCExplicit) {
3776  // Inherit the CC from the previous declaration if it was specified
3777  // there but not here.
3778  NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3779  RequiresAdjustment = true;
3780  } else if (Old->getBuiltinID()) {
3781  // Builtin attribute isn't propagated to the new one yet at this point,
3782  // so we check if the old one is a builtin.
3783 
3784  // Calling Conventions on a Builtin aren't really useful and setting a
3785  // default calling convention and cdecl'ing some builtin redeclarations is
3786  // common, so warn and ignore the calling convention on the redeclaration.
3787  Diag(New->getLocation(), diag::warn_cconv_unsupported)
3788  << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3789  << (int)CallingConventionIgnoredReason::BuiltinFunction;
3790  NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3791  RequiresAdjustment = true;
3792  } else {
3793  // Calling conventions aren't compatible, so complain.
3794  bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3795  Diag(New->getLocation(), diag::err_cconv_change)
3796  << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3797  << !FirstCCExplicit
3798  << (!FirstCCExplicit ? "" :
3799  FunctionType::getNameForCallConv(FI.getCC()));
3800 
3801  // Put the note on the first decl, since it is the one that matters.
3802  Diag(First->getLocation(), diag::note_previous_declaration);
3803  return true;
3804  }
3805  }
3806 
3807  // FIXME: diagnose the other way around?
3808  if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3809  NewTypeInfo = NewTypeInfo.withNoReturn(true);
3810  RequiresAdjustment = true;
3811  }
3812 
3813  // Merge regparm attribute.
3814  if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3815  OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3816  if (NewTypeInfo.getHasRegParm()) {
3817  Diag(New->getLocation(), diag::err_regparm_mismatch)
3818  << NewType->getRegParmType()
3819  << OldType->getRegParmType();
3820  Diag(OldLocation, diag::note_previous_declaration);
3821  return true;
3822  }
3823 
3824  NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3825  RequiresAdjustment = true;
3826  }
3827 
3828  // Merge ns_returns_retained attribute.
3829  if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3830  if (NewTypeInfo.getProducesResult()) {
3831  Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3832  << "'ns_returns_retained'";
3833  Diag(OldLocation, diag::note_previous_declaration);
3834  return true;
3835  }
3836 
3837  NewTypeInfo = NewTypeInfo.withProducesResult(true);
3838  RequiresAdjustment = true;
3839  }
3840 
3841  if (OldTypeInfo.getNoCallerSavedRegs() !=
3842  NewTypeInfo.getNoCallerSavedRegs()) {
3843  if (NewTypeInfo.getNoCallerSavedRegs()) {
3844  AnyX86NoCallerSavedRegistersAttr *Attr =
3845  New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3846  Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3847  Diag(OldLocation, diag::note_previous_declaration);
3848  return true;
3849  }
3850 
3851  NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3852  RequiresAdjustment = true;
3853  }
3854 
3855  if (RequiresAdjustment) {
3856  const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3857  AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3858  New->setType(QualType(AdjustedType, 0));
3859  NewQType = Context.getCanonicalType(New->getType());
3860  }
3861 
3862  // If this redeclaration makes the function inline, we may need to add it to
3863  // UndefinedButUsed.
3864  if (!Old->isInlined() && New->isInlined() &&
3865  !New->hasAttr<GNUInlineAttr>() &&
3866  !getLangOpts().GNUInline &&
3867  Old->isUsed(false) &&
3868  !Old->isDefined() && !New->isThisDeclarationADefinition())
3869  UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3870  SourceLocation()));
3871 
3872  // If this redeclaration makes it newly gnu_inline, we don't want to warn
3873  // about it.
3874  if (New->hasAttr<GNUInlineAttr>() &&
3875  Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3876  UndefinedButUsed.erase(Old->getCanonicalDecl());
3877  }
3878 
3879  // If pass_object_size params don't match up perfectly, this isn't a valid
3880  // redeclaration.
3881  if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3882  !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3883  Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3884  << New->getDeclName();
3885  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3886  return true;
3887  }
3888 
3889  if (getLangOpts().CPlusPlus) {
3890  // C++1z [over.load]p2
3891  // Certain function declarations cannot be overloaded:
3892  // -- Function declarations that differ only in the return type,
3893  // the exception specification, or both cannot be overloaded.
3894 
3895  // Check the exception specifications match. This may recompute the type of
3896  // both Old and New if it resolved exception specifications, so grab the
3897  // types again after this. Because this updates the type, we do this before
3898  // any of the other checks below, which may update the "de facto" NewQType
3899  // but do not necessarily update the type of New.
3900  if (CheckEquivalentExceptionSpec(Old, New))
3901  return true;
3902  OldQType = Context.getCanonicalType(Old->getType());
3903  NewQType = Context.getCanonicalType(New->getType());
3904 
3905  // Go back to the type source info to compare the declared return types,
3906  // per C++1y [dcl.type.auto]p13:
3907  // Redeclarations or specializations of a function or function template
3908  // with a declared return type that uses a placeholder type shall also
3909  // use that placeholder, not a deduced type.
3910  QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3911  QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3912  if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3913  canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3914  OldDeclaredReturnType)) {
3915  QualType ResQT;
3916  if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3917  OldDeclaredReturnType->isObjCObjectPointerType())
3918  // FIXME: This does the wrong thing for a deduced return type.
3919  ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3920  if (ResQT.isNull()) {
3921  if (New->isCXXClassMember() && New->isOutOfLine())
3922  Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3923  << New << New->getReturnTypeSourceRange();
3924  else
3925  Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3926  << New->getReturnTypeSourceRange();
3927  Diag(OldLocation, PrevDiag) << Old << Old->getType()
3928  << Old->getReturnTypeSourceRange();
3929  return true;
3930  }
3931  else
3932  NewQType = ResQT;
3933  }
3934 
3935  QualType OldReturnType = OldType->getReturnType();
3936  QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3937  if (OldReturnType != NewReturnType) {
3938  // If this function has a deduced return type and has already been
3939  // defined, copy the deduced value from the old declaration.
3940  AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3941  if (OldAT && OldAT->isDeduced()) {
3942  QualType DT = OldAT->getDeducedType();
3943  if (DT.isNull()) {
3944  New->setType(SubstAutoTypeDependent(New->getType()));
3945  NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3946  } else {
3947  New->setType(SubstAutoType(New->getType(), DT));
3948  NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3949  }
3950  }
3951  }
3952 
3953  const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3954  CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3955  if (OldMethod && NewMethod) {
3956  // Preserve triviality.
3957  NewMethod->setTrivial(OldMethod->isTrivial());
3958 
3959  // MSVC allows explicit template specialization at class scope:
3960  // 2 CXXMethodDecls referring to the same function will be injected.
3961  // We don't want a redeclaration error.
3962  bool IsClassScopeExplicitSpecialization =
3963  OldMethod->isFunctionTemplateSpecialization() &&
3964  NewMethod->isFunctionTemplateSpecialization();
3965  bool isFriend = NewMethod->getFriendObjectKind();
3966 
3967  if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3968  !IsClassScopeExplicitSpecialization) {
3969  // -- Member function declarations with the same name and the
3970  // same parameter types cannot be overloaded if any of them
3971  // is a static member function declaration.
3972  if (OldMethod->isStatic() != NewMethod->isStatic()) {
3973  Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3974  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3975  return true;
3976  }
3977 
3978  // C++ [class.mem]p1:
3979  // [...] A member shall not be declared twice in the
3980  // member-specification, except that a nested class or member
3981  // class template can be declared and then later defined.
3982  if (!inTemplateInstantiation()) {
3983  unsigned NewDiag;
3984  if (isa<CXXConstructorDecl>(OldMethod))
3985  NewDiag = diag::err_constructor_redeclared;
3986  else if (isa<CXXDestructorDecl>(NewMethod))
3987  NewDiag = diag::err_destructor_redeclared;
3988  else if (isa<CXXConversionDecl>(NewMethod))
3989  NewDiag = diag::err_conv_function_redeclared;
3990  else
3991  NewDiag = diag::err_member_redeclared;
3992 
3993  Diag(New->getLocation(), NewDiag);
3994  } else {
3995  Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3996  << New << New->getType();
3997  }
3998  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3999  return true;
4000 
4001  // Complain if this is an explicit declaration of a special
4002  // member that was initially declared implicitly.
4003  //
4004  // As an exception, it's okay to befriend such methods in order
4005  // to permit the implicit constructor/destructor/operator calls.
4006  } else if (OldMethod->isImplicit()) {
4007  if (isFriend) {
4008  NewMethod->setImplicit();
4009  } else {
4010  Diag(NewMethod->getLocation(),
4011  diag::err_definition_of_implicitly_declared_member)
4012  << New << getSpecialMember(OldMethod);
4013  return true;
4014  }
4015  } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4016  Diag(NewMethod->getLocation(),
4017  diag::err_definition_of_explicitly_defaulted_member)
4018  << getSpecialMember(OldMethod);
4019  return true;
4020  }
4021  }
4022 
4023  // C++11 [dcl.attr.noreturn]p1:
4024  // The first declaration of a function shall specify the noreturn
4025  // attribute if any declaration of that function specifies the noreturn
4026  // attribute.
4027  if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4028  if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4029  Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4030  << NRA;
4031  Diag(Old->getLocation(), diag::note_previous_declaration);
4032  }
4033 
4034  // C++11 [dcl.attr.depend]p2:
4035  // The first declaration of a function shall specify the
4036  // carries_dependency attribute for its declarator-id if any declaration
4037  // of the function specifies the carries_dependency attribute.
4038  const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4039  if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4040  Diag(CDA->getLocation(),
4041  diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4042  Diag(Old->getFirstDecl()->getLocation(),
4043  diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4044  }
4045 
4046  // (C++98 8.3.5p3):
4047  // All declarations for a function shall agree exactly in both the
4048  // return type and the parameter-type-list.
4049  // We also want to respect all the extended bits except noreturn.
4050 
4051  // noreturn should now match unless the old type info didn't have it.
4052  QualType OldQTypeForComparison = OldQType;
4053  if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4054  auto *OldType = OldQType->castAs<FunctionProtoType>();
4055  const FunctionType *OldTypeForComparison
4056  = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4057  OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4058  assert(OldQTypeForComparison.isCanonical());
4059  }
4060 
4061  if (haveIncompatibleLanguageLinkages(Old, New)) {
4062  // As a special case, retain the language linkage from previous
4063  // declarations of a friend function as an extension.
4064  //
4065  // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4066  // and is useful because there's otherwise no way to specify language
4067  // linkage within class scope.
4068  //
4069  // Check cautiously as the friend object kind isn't yet complete.
4070  if (New->getFriendObjectKind() != Decl::FOK_None) {
4071  Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4072  Diag(OldLocation, PrevDiag);
4073  } else {
4074  Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4075  Diag(OldLocation, PrevDiag);
4076  return true;
4077  }
4078  }
4079 
4080  // If the function types are compatible, merge the declarations. Ignore the
4081  // exception specifier because it was already checked above in
4082  // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4083  // about incompatible types under -fms-compatibility.
4084  if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4085  NewQType))
4086  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4087 
4088  // If the types are imprecise (due to dependent constructs in friends or
4089  // local extern declarations), it's OK if they differ. We'll check again
4090  // during instantiation.
4091  if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4092  return false;
4093 
4094  // Fall through for conflicting redeclarations and redefinitions.
4095  }
4096 
4097  // C: Function types need to be compatible, not identical. This handles
4098  // duplicate function decls like "void f(int); void f(enum X);" properly.
4099  if (!getLangOpts().CPlusPlus) {
4100  // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4101  // type is specified by a function definition that contains a (possibly
4102  // empty) identifier list, both shall agree in the number of parameters
4103  // and the type of each parameter shall be compatible with the type that
4104  // results from the application of default argument promotions to the
4105  // type of the corresponding identifier. ...
4106  // This cannot be handled by ASTContext::typesAreCompatible() because that
4107  // doesn't know whether the function type is for a definition or not when
4108  // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4109  // we need to cover here is that the number of arguments agree as the
4110  // default argument promotion rules were already checked by
4111  // ASTContext::typesAreCompatible().
4112  if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4113  Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4114  if (Old->hasInheritedPrototype())
4115  Old = Old->getCanonicalDecl();
4116  Diag(New->getLocation(), diag::err_conflicting_types) << New;
4117  Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4118  return true;
4119  }
4120 
4121  // If we are merging two functions where only one of them has a prototype,
4122  // we may have enough information to decide to issue a diagnostic that the
4123  // function without a protoype will change behavior in C2x. This handles
4124  // cases like:
4125  // void i(); void i(int j);
4126  // void i(int j); void i();
4127  // void i(); void i(int j) {}
4128  // See ActOnFinishFunctionBody() for other cases of the behavior change
4129  // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4130  // type without a prototype.
4131  if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4132  !New->isImplicit() && !Old->isImplicit()) {
4133  const FunctionDecl *WithProto, *WithoutProto;
4134  if (New->hasWrittenPrototype()) {
4135  WithProto = New;
4136  WithoutProto = Old;
4137  } else {
4138  WithProto = Old;
4139  WithoutProto = New;
4140  }
4141 
4142  if (WithProto->getNumParams() != 0) {
4143  if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4144  // The one without the prototype will be changing behavior in C2x, so
4145  // warn about that one so long as it's a user-visible declaration.
4146  bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4147  if (WithoutProto == New)
4148  IsWithoutProtoADef = NewDeclIsDefn;
4149  else
4150  IsWithProtoADef = NewDeclIsDefn;
4151  Diag(WithoutProto->getLocation(),
4152  diag::warn_non_prototype_changes_behavior)
4153  << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4154  << (WithoutProto == Old) << IsWithProtoADef;
4155 
4156  // The reason the one without the prototype will be changing behavior
4157  // is because of the one with the prototype, so note that so long as
4158  // it's a user-visible declaration. There is one exception to this:
4159  // when the new declaration is a definition without a prototype, the
4160  // old declaration with a prototype is not the cause of the issue,
4161  // and that does not need to be noted because the one with a
4162  // prototype will not change behavior in C2x.
4163  if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4164  !IsWithoutProtoADef)
4165  Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4166  }
4167  }
4168  }
4169 
4170  if (Context.typesAreCompatible(OldQType, NewQType)) {
4171  const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4172  const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4173  const FunctionProtoType *OldProto = nullptr;
4174  if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4175  (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4176  // The old declaration provided a function prototype, but the
4177  // new declaration does not. Merge in the prototype.
4178  assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4179  NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4180  OldProto->getParamTypes(),
4181  OldProto->getExtProtoInfo());
4182  New->setType(NewQType);
4183  New->setHasInheritedPrototype();
4184 
4185  // Synthesize parameters with the same types.
4187  for (const auto &ParamType : OldProto->param_types()) {
4189  Context, New, SourceLocation(), SourceLocation(), nullptr,
4190  ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4191  Param->setScopeInfo(0, Params.size());
4192  Param->setImplicit();
4193  Params.push_back(Param);
4194  }
4195 
4196  New->setParams(Params);
4197  }
4198 
4199  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4200  }
4201  }
4202 
4203  // Check if the function types are compatible when pointer size address
4204  // spaces are ignored.
4205  if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4206  return false;
4207 
4208  // GNU C permits a K&R definition to follow a prototype declaration
4209  // if the declared types of the parameters in the K&R definition
4210  // match the types in the prototype declaration, even when the
4211  // promoted types of the parameters from the K&R definition differ
4212  // from the types in the prototype. GCC then keeps the types from
4213  // the prototype.
4214  //
4215  // If a variadic prototype is followed by a non-variadic K&R definition,
4216  // the K&R definition becomes variadic. This is sort of an edge case, but
4217  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4218  // C99 6.9.1p8.
4219  if (!getLangOpts().CPlusPlus &&
4220  Old->hasPrototype() && !New->hasPrototype() &&
4221  New->getType()->getAs<FunctionProtoType>() &&
4222  Old->getNumParams() == New->getNumParams()) {
4223  SmallVector<QualType, 16> ArgTypes;
4225  const FunctionProtoType *OldProto
4226  = Old->getType()->getAs<FunctionProtoType>();
4227  const FunctionProtoType *NewProto
4228  = New->getType()->getAs<FunctionProtoType>();
4229 
4230  // Determine whether this is the GNU C extension.
4231  QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4232  NewProto->getReturnType());
4233  bool LooseCompatible = !MergedReturn.isNull();
4234  for (unsigned Idx = 0, End = Old->getNumParams();
4235  LooseCompatible && Idx != End; ++Idx) {
4236  ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4237  ParmVarDecl *NewParm = New->getParamDecl(Idx);
4238  if (Context.typesAreCompatible(OldParm->getType(),
4239  NewProto->getParamType(Idx))) {
4240  ArgTypes.push_back(NewParm->getType());
4241  } else if (Context.typesAreCompatible(OldParm->getType(),
4242  NewParm->getType(),
4243  /*CompareUnqualified=*/true)) {
4244  GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4245  NewProto->getParamType(Idx) };
4246  Warnings.push_back(Warn);
4247  ArgTypes.push_back(NewParm->getType());
4248  } else
4249  LooseCompatible = false;
4250  }
4251 
4252  if (LooseCompatible) {
4253  for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4254  Diag(Warnings[Warn].NewParm->getLocation(),
4255  diag::ext_param_promoted_not_compatible_with_prototype)
4256  << Warnings[Warn].PromotedType
4257  << Warnings[Warn].OldParm->getType();
4258  if (Warnings[Warn].OldParm->getLocation().isValid())
4259  Diag(Warnings[Warn].OldParm->getLocation(),
4260  diag::note_previous_declaration);
4261  }
4262 
4263  if (MergeTypeWithOld)
4264  New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4265  OldProto->getExtProtoInfo()));
4266  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4267  }
4268 
4269  // Fall through to diagnose conflicting types.
4270  }
4271 
4272  // A function that has already been declared has been redeclared or
4273  // defined with a different type; show an appropriate diagnostic.
4274 
4275  // If the previous declaration was an implicitly-generated builtin
4276  // declaration, then at the very least we should use a specialized note.
4277  unsigned BuiltinID;
4278  if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4279  // If it's actually a library-defined builtin function like 'malloc'
4280  // or 'printf', just warn about the incompatible redeclaration.
4281  if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4282  Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4283  Diag(OldLocation, diag::note_previous_builtin_declaration)
4284  << Old << Old->getType();
4285  return false;
4286  }
4287 
4288  PrevDiag = diag::note_previous_builtin_declaration;
4289  }
4290 
4291  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4292  Diag(OldLocation, PrevDiag) << Old << Old->getType();
4293  return true;
4294 }
4295 
4296 /// Completes the merge of two function declarations that are
4297 /// known to be compatible.
4298 ///
4299 /// This routine handles the merging of attributes and other
4300 /// properties of function declarations from the old declaration to
4301 /// the new declaration, once we know that New is in fact a
4302 /// redeclaration of Old.
4303 ///
4304 /// \returns false
4306  Scope *S, bool MergeTypeWithOld) {
4307  // Merge the attributes
4308  mergeDeclAttributes(New, Old);
4309 
4310  // Merge "pure" flag.
4311  if (Old->isPure())
4312  New->setPure();
4313 
4314  // Merge "used" flag.
4315  if (Old->getMostRecentDecl()->isUsed(false))
4316  New->setIsUsed();
4317 
4318  // Merge attributes from the parameters. These can mismatch with K&R
4319  // declarations.
4320  if (New->getNumParams() == Old->getNumParams())
4321  for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4322  ParmVarDecl *NewParam = New->getParamDecl(i);
4323  ParmVarDecl *OldParam = Old->getParamDecl(i);
4324  mergeParamDeclAttributes(NewParam, OldParam, *this);
4325  mergeParamDeclTypes(NewParam, OldParam, *this);
4326  }
4327 
4328  if (getLangOpts().CPlusPlus)
4329  return MergeCXXFunctionDecl(New, Old, S);
4330 
4331  // Merge the function types so the we get the composite types for the return
4332  // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4333  // was visible.
4334  QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4335  if (!Merged.isNull() && MergeTypeWithOld)
4336  New->setType(Merged);
4337 
4338  return false;
4339 }
4340 
4342  ObjCMethodDecl *oldMethod) {
4343  // Merge the attributes, including deprecated/unavailable
4344  AvailabilityMergeKind MergeKind =
4345  isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4346  ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4347  : AMK_ProtocolImplementation)
4348  : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4349  : AMK_Override;
4350 
4351  mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4352 
4353  // Merge attributes from the parameters.
4355  oe = oldMethod->param_end();
4357  ni = newMethod->param_begin(), ne = newMethod->param_end();
4358  ni != ne && oi != oe; ++ni, ++oi)
4359  mergeParamDeclAttributes(*ni, *oi, *this);
4360 
4361  CheckObjCMethodOverride(newMethod, oldMethod);
4362 }
4363 
4364 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4365  assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4366 
4368  ? diag::err_redefinition_different_type
4369  : diag::err_redeclaration_different_type)
4370  << New->getDeclName() << New->getType() << Old->getType();
4371 
4372  diag::kind PrevDiag;
4373  SourceLocation OldLocation;
4374  std::tie(PrevDiag, OldLocation)
4376  S.Diag(OldLocation, PrevDiag);
4377  New->setInvalidDecl();
4378 }
4379 
4380 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4381 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
4382 /// emitting diagnostics as appropriate.
4383 ///
4384 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4385 /// to here in AddInitializerToDecl. We can't check them before the initializer
4386 /// is attached.
4388  bool MergeTypeWithOld) {
4389  if (New->isInvalidDecl() || Old->isInvalidDecl())
4390  return;
4391 
4392  QualType MergedT;
4393  if (getLangOpts().CPlusPlus) {
4394  if (New->getType()->isUndeducedType()) {
4395  // We don't know what the new type is until the initializer is attached.
4396  return;
4397  } else if (Context.hasSameType(New->getType(), Old->getType())) {
4398  // These could still be something that needs exception specs checked.
4399  return MergeVarDeclExceptionSpecs(New, Old);
4400  }
4401  // C++ [basic.link]p10:
4402  // [...] the types specified by all declarations referring to a given
4403  // object or function shall be identical, except that declarations for an
4404  // array object can specify array types that differ by the presence or
4405  // absence of a major array bound (8.3.4).
4406  else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4407  const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4408  const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4409 
4410  // We are merging a variable declaration New into Old. If it has an array
4411  // bound, and that bound differs from Old's bound, we should diagnose the
4412  // mismatch.
4413  if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4414  for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4415  PrevVD = PrevVD->getPreviousDecl()) {
4416  QualType PrevVDTy = PrevVD->getType();
4417  if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4418  continue;
4419 
4420  if (!Context.hasSameType(New->getType(), PrevVDTy))
4421  return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4422  }
4423  }
4424 
4425  if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4426  if (Context.hasSameType(OldArray->getElementType(),
4427  NewArray->getElementType()))
4428  MergedT = New->getType();
4429  }
4430  // FIXME: Check visibility. New is hidden but has a complete type. If New
4431  // has no array bound, it should not inherit one from Old, if Old is not
4432  // visible.
4433  else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4434  if (Context.hasSameType(OldArray->getElementType(),
4435  NewArray->getElementType()))
4436  MergedT = Old->getType();
4437  }
4438  }
4439  else if (New->getType()->isObjCObjectPointerType() &&
4440  Old->getType()->isObjCObjectPointerType()) {
4441  MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4442  Old->getType());
4443  }
4444  } else {
4445  // C 6.2.7p2:
4446  // All declarations that refer to the same object or function shall have
4447  // compatible type.
4448  MergedT = Context.mergeTypes(New->getType(), Old->getType());
4449  }
4450  if (MergedT.isNull()) {
4451  // It's OK if we couldn't merge types if either type is dependent, for a
4452  // block-scope variable. In other cases (static data members of class
4453  // templates, variable templates, ...), we require the types to be
4454  // equivalent.
4455  // FIXME: The C++ standard doesn't say anything about this.
4456  if ((New->getType()->isDependentType() ||
4457  Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4458  // If the old type was dependent, we can't merge with it, so the new type
4459  // becomes dependent for now. We'll reproduce the original type when we
4460  // instantiate the TypeSourceInfo for the variable.
4461  if (!New->getType()->isDependentType() && MergeTypeWithOld)
4462  New->setType(Context.DependentTy);
4463  return;
4464  }
4465  return diagnoseVarDeclTypeMismatch(*this, New, Old);
4466  }
4467 
4468  // Don't actually update the type on the new declaration if the old
4469  // declaration was an extern declaration in a different scope.
4470  if (MergeTypeWithOld)
4471  New->setType(MergedT);
4472 }
4473 
4474 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4476  // C11 6.2.7p4:
4477  // For an identifier with internal or external linkage declared
4478  // in a scope in which a prior declaration of that identifier is
4479  // visible, if the prior declaration specifies internal or
4480  // external linkage, the type of the identifier at the later
4481  // declaration becomes the composite type.
4482  //
4483  // If the variable isn't visible, we do not merge with its type.
4484  if (Previous.isShadowed())
4485  return false;
4486 
4487  if (S.getLangOpts().CPlusPlus) {
4488  // C++11 [dcl.array]p3:
4489  // If there is a preceding declaration of the entity in the same
4490  // scope in which the bound was specified, an omitted array bound
4491  // is taken to be the same as in that earlier declaration.
4492  return NewVD->isPreviousDeclInSameBlockScope() ||
4493  (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4495  } else {
4496  // If the old declaration was function-local, don't merge with its
4497  // type unless we're in the same function.
4498  return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4499  OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4500  }
4501 }
4502 
4503 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4504 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4505 /// situation, merging decls or emitting diagnostics as appropriate.
4506 ///
4507 /// Tentative definition rules (C99 6.9.2p2) are checked by
4508 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4509 /// definitions here, since the initializer hasn't been attached.
4510 ///
4512  // If the new decl is already invalid, don't do any other checking.
4513  if (New->isInvalidDecl())
4514  return;
4515 
4516  if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4517  return;
4518 
4519  VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4520 
4521  // Verify the old decl was also a variable or variable template.
4522  VarDecl *Old = nullptr;
4523  VarTemplateDecl *OldTemplate = nullptr;
4524  if (Previous.isSingleResult()) {
4525  if (NewTemplate) {
4526  OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4527  Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4528 
4529  if (auto *Shadow =
4530  dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4531  if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4532  return New->setInvalidDecl();
4533  } else {
4534  Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4535 
4536  if (auto *Shadow =
4537  dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4538  if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4539  return New->setInvalidDecl();
4540  }
4541  }
4542  if (!Old) {
4543  Diag(New->getLocation(), diag::err_redefinition_different_kind)
4544  << New->getDeclName();
4545  notePreviousDefinition(Previous.getRepresentativeDecl(),
4546  New->getLocation());
4547  return New->setInvalidDecl();
4548  }
4549 
4550  // If the old declaration was found in an inline namespace and the new
4551  // declaration was qualified, update the DeclContext to match.
4553 
4554  // Ensure the template parameters are compatible.
4555  if (NewTemplate &&
4556  !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4557  OldTemplate->getTemplateParameters(),
4558  /*Complain=*/true, TPL_TemplateMatch))
4559  return New->setInvalidDecl();
4560 
4561  // C++ [class.mem]p1:
4562  // A member shall not be declared twice in the member-specification [...]
4563  //
4564  // Here, we need only consider static data members.
4565  if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4566  Diag(New->getLocation(), diag::err_duplicate_member)
4567  << New->getIdentifier();
4568  Diag(Old->getLocation(), diag::note_previous_declaration);
4569  New->setInvalidDecl();
4570  }
4571 
4572  mergeDeclAttributes(New, Old);
4573  // Warn if an already-declared variable is made a weak_import in a subsequent
4574  // declaration
4575  if (New->hasAttr<WeakImportAttr>() &&
4576  Old->getStorageClass() == SC_None &&
4577  !Old->hasAttr<WeakImportAttr>()) {
4578  Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4579  Diag(Old->getLocation(), diag::note_previous_declaration);
4580  // Remove weak_import attribute on new declaration.
4581  New->dropAttr<WeakImportAttr>();
4582  }
4583 
4584  if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4585  if (!Old->hasAttr<InternalLinkageAttr>()) {
4586  Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4587  << ILA;
4588  Diag(Old->getLocation(), diag::note_previous_declaration);
4589  New->dropAttr<InternalLinkageAttr>();
4590  }
4591 
4592  // Merge the types.
4593  VarDecl *MostRecent = Old->getMostRecentDecl();
4594  if (MostRecent != Old) {
4595  MergeVarDeclTypes(New, MostRecent,
4596  mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4597  if (New->isInvalidDecl())
4598  return;
4599  }
4600 
4601  MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4602  if (New->isInvalidDecl())
4603  return;
4604 
4605  diag::kind PrevDiag;
4606  SourceLocation OldLocation;
4607  std::tie(PrevDiag, OldLocation) =
4609 
4610  // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4611  if (New->getStorageClass() == SC_Static &&
4612  !New->isStaticDataMember() &&
4613  Old->hasExternalFormalLinkage()) {
4614  if (getLangOpts().MicrosoftExt) {
4615  Diag(New->getLocation(), diag::ext_static_non_static)
4616  << New->getDeclName();
4617  Diag(OldLocation, PrevDiag);
4618  } else {
4619  Diag(New->getLocation(), diag::err_static_non_static)
4620  << New->getDeclName();
4621  Diag(OldLocation, PrevDiag);
4622  return New->setInvalidDecl();
4623  }
4624  }
4625  // C99 6.2.2p4:
4626  // For an identifier declared with the storage-class specifier
4627  // extern in a scope in which a prior declaration of that
4628  // identifier is visible,23) if the prior declaration specifies
4629  // internal or external linkage, the linkage of the identifier at
4630  // the later declaration is the same as the linkage specified at
4631  // the prior declaration. If no prior declaration is visible, or
4632  // if the prior declaration specifies no linkage, then the
4633  // identifier has external linkage.
4634  if (New->hasExternalStorage() && Old->hasLinkage())
4635  /* Okay */;
4636  else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4637  !New->isStaticDataMember() &&
4639  Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4640  Diag(OldLocation, PrevDiag);
4641  return New->setInvalidDecl();
4642  }
4643 
4644  // Check if extern is followed by non-extern and vice-versa.
4645  if (New->hasExternalStorage() &&
4646  !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4647  Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4648  Diag(OldLocation, PrevDiag);
4649  return New->setInvalidDecl();
4650  }
4651  if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4652  !New->hasExternalStorage()) {
4653  Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4654  Diag(OldLocation, PrevDiag);
4655  return New->setInvalidDecl();
4656  }
4657 
4658  if (CheckRedeclarationInModule(New, Old))
4659  return;
4660 
4661  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4662 
4663  // FIXME: The test for external storage here seems wrong? We still
4664  // need to check for mismatches.
4665  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4666  // Don't complain about out-of-line definitions of static members.
4667  !(Old->getLexicalDeclContext()->isRecord() &&
4668  !New->getLexicalDeclContext()->isRecord())) {
4669  Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4670  Diag(OldLocation, PrevDiag);
4671  return New->setInvalidDecl();
4672  }
4673 
4674  if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4675  if (VarDecl *Def = Old->getDefinition()) {
4676  // C++1z [dcl.fcn.spec]p4:
4677  // If the definition of a variable appears in a translation unit before
4678  // its first declaration as inline, the program is ill-formed.
4679  Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4680  Diag(Def->getLocation(), diag::note_previous_definition);
4681  }
4682  }
4683 
4684  // If this redeclaration makes the variable inline, we may need to add it to
4685  // UndefinedButUsed.
4686  if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4687  !Old->getDefinition() && !New->isThisDeclarationADefinition())
4688  UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4689  SourceLocation()));
4690 
4691  if (New->getTLSKind() != Old->getTLSKind()) {
4692  if (!Old->getTLSKind()) {
4693  Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4694  Diag(OldLocation, PrevDiag);
4695  } else if (!New->getTLSKind()) {
4696  Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4697  Diag(OldLocation, PrevDiag);
4698  } else {
4699  // Do not allow redeclaration to change the variable between requiring
4700  // static and dynamic initialization.
4701  // FIXME: GCC allows this, but uses the TLS keyword on the first
4702  // declaration to determine the kind. Do we need to be compatible here?
4703  Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4704  << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4705  Diag(OldLocation, PrevDiag);
4706  }
4707  }
4708 
4709  // C++ doesn't have tentative definitions, so go right ahead and check here.
4710  if (getLangOpts().CPlusPlus) {
4711  if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4712  Old->getCanonicalDecl()->isConstexpr()) {
4713  // This definition won't be a definition any more once it's been merged.
4714  Diag(New->getLocation(),
4715  diag::warn_deprecated_redundant_constexpr_static_def);
4716  } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4717  VarDecl *Def = Old->getDefinition();
4718  if (Def && checkVarDeclRedefinition(Def, New))
4719  return;
4720  }
4721  }
4722 
4723  if (haveIncompatibleLanguageLinkages(Old, New)) {
4724  Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4725  Diag(OldLocation, PrevDiag);
4726  New->setInvalidDecl();
4727  return;
4728  }
4729 
4730  // Merge "used" flag.
4731  if (Old->getMostRecentDecl()->isUsed(false))
4732  New->setIsUsed();
4733 
4734  // Keep a chain of previous declarations.
4735  New->setPreviousDecl(Old);
4736  if (NewTemplate)
4737  NewTemplate->setPreviousDecl(OldTemplate);
4738 
4739  // Inherit access appropriately.
4740  New->setAccess(Old->getAccess());
4741  if (NewTemplate)
4742  NewTemplate->setAccess(New->getAccess());
4743 
4744  if (Old->isInline())
4745  New->setImplicitlyInline();
4746 }
4747 
4749  SourceManager &SrcMgr = getSourceManager();
4750  auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4751  auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4752  auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4753  auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4754  auto &HSI = PP.getHeaderSearchInfo();
4755  StringRef HdrFilename =
4756  SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4757 
4758  auto noteFromModuleOrInclude = [&](Module *Mod,
4759  SourceLocation IncLoc) -> bool {
4760  // Redefinition errors with modules are common with non modular mapped
4761  // headers, example: a non-modular header H in module A that also gets
4762  // included directly in a TU. Pointing twice to the same header/definition
4763  // is confusing, try to get better diagnostics when modules is on.
4764  if (IncLoc.isValid()) {
4765  if (Mod) {
4766  Diag(IncLoc, diag::note_redefinition_modules_same_file)
4767  << HdrFilename.str() << Mod->getFullModuleName();
4768  if (!Mod->DefinitionLoc.isInvalid())
4769  Diag(Mod->DefinitionLoc, diag::note_defined_here)
4770  << Mod->getFullModuleName();
4771  } else {
4772  Diag(IncLoc, diag::note_redefinition_include_same_file)
4773  << HdrFilename.str();
4774  }
4775  return true;
4776  }
4777 
4778  return false;
4779  };
4780 
4781  // Is it the same file and same offset? Provide more information on why
4782  // this leads to a redefinition error.
4783  if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4784  SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4785  SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4786  bool EmittedDiag =
4787  noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4788  EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4789 
4790  // If the header has no guards, emit a note suggesting one.
4791  if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4792  Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4793 
4794  if (EmittedDiag)
4795  return;
4796  }
4797 
4798  // Redefinition coming from different files or couldn't do better above.
4799  if (Old->getLocation().isValid())
4800  Diag(Old->getLocation(), diag::note_previous_definition);
4801 }
4802 
4803 /// We've just determined that \p Old and \p New both appear to be definitions
4804 /// of the same variable. Either diagnose or fix the problem.
4806  if (!hasVisibleDefinition(Old) &&
4807  (New->getFormalLinkage() == InternalLinkage ||
4808  New->isInline() ||
4809  isa<VarTemplateSpecializationDecl>(New) ||
4810  New->getDescribedVarTemplate() ||
4812  New->getDeclContext()->isDependentContext())) {
4813  // The previous definition is hidden, and multiple definitions are
4814  // permitted (in separate TUs). Demote this to a declaration.
4816 
4817  // Make the canonical definition visible.
4818  if (auto *OldTD = Old->getDescribedVarTemplate())
4819  makeMergedDefinitionVisible(OldTD);
4820  makeMergedDefinitionVisible(Old);
4821  return false;
4822  } else {
4823  Diag(New->getLocation(), diag::err_redefinition) << New;
4824  notePreviousDefinition(Old, New->getLocation());
4825  New->setInvalidDecl();
4826  return true;
4827  }
4828 }
4829 
4830 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4831 /// no declarator (e.g. "struct foo;") is parsed.
4833  DeclSpec &DS,
4834  const ParsedAttributesView &DeclAttrs,
4835  RecordDecl *&AnonRecord) {
4836  return ParsedFreeStandingDeclSpec(
4837  S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4838 }
4839 
4840 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4841 // disambiguate entities defined in different scopes.
4842 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4843 // compatibility.
4844 // We will pick our mangling number depending on which version of MSVC is being
4845 // targeted.
4846 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4848  ? S->getMSCurManglingNumber()
4849  : S->getMSLastManglingNumber();
4850 }
4851 
4852 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4853  if (!Context.getLangOpts().CPlusPlus)
4854  return;
4855 
4856  if (isa<CXXRecordDecl>(Tag->getParent())) {
4857  // If this tag is the direct child of a class, number it if
4858  // it is anonymous.
4859  if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4860  return;
4861  MangleNumberingContext &MCtx =
4862  Context.getManglingNumberContext(Tag->getParent());
4863  Context.setManglingNumber(
4864  Tag, MCtx.getManglingNumber(
4865  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4866  return;
4867  }
4868 
4869  // If this tag isn't a direct child of a class, number it if it is local.
4870  MangleNumberingContext *MCtx;
4871  Decl *ManglingContextDecl;
4872  std::tie(MCtx, ManglingContextDecl) =
4873  getCurrentMangleNumberContext(Tag->getDeclContext());
4874  if (MCtx) {
4875  Context.setManglingNumber(
4876  Tag, MCtx->getManglingNumber(
4877  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4878  }
4879 }
4880 
4881 namespace {
4882 struct NonCLikeKind {
4883  enum {
4884  None,
4885  BaseClass,
4886  DefaultMemberInit,
4887  Lambda,
4888  Friend,
4889  OtherMember,
4890  Invalid,
4891  } Kind = None;
4892  SourceRange Range;
4893 
4894  explicit operator bool() { return Kind != None; }
4895 };
4896 }
4897 
4898 /// Determine whether a class is C-like, according to the rules of C++
4899 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4900 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4901  if (RD->isInvalidDecl())
4902  return {NonCLikeKind::Invalid, {}};
4903 
4904  // C++ [dcl.typedef]p9: [P1766R1]
4905  // An unnamed class with a typedef name for linkage purposes shall not
4906  //
4907  // -- have any base classes
4908  if (RD->getNumBases())
4909  return {NonCLikeKind::BaseClass,
4911  RD->bases_end()[-1].getEndLoc())};
4912  bool Invalid = false;
4913  for (Decl *D : RD->decls()) {
4914  // Don't complain about things we already diagnosed.
4915  if (D->isInvalidDecl()) {
4916  Invalid = true;
4917  continue;
4918  }
4919 
4920  // -- have any [...] default member initializers
4921  if (auto *FD = dyn_cast<FieldDecl>(D)) {
4922  if (FD->hasInClassInitializer()) {
4923  auto *Init = FD->getInClassInitializer();
4924  return {NonCLikeKind::DefaultMemberInit,
4925  Init ? Init->getSourceRange() : D->getSourceRange()};
4926  }
4927  continue;
4928  }
4929 
4930  // FIXME: We don't allow friend declarations. This violates the wording of
4931  // P1766, but not the intent.
4932  if (isa<FriendDecl>(D))
4933  return {NonCLikeKind::Friend, D->getSourceRange()};
4934 
4935  // -- declare any members other than non-static data members, member
4936  // enumerations, or member classes,
4937  if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4938  isa<EnumDecl>(D))
4939  continue;
4940  auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4941  if (!MemberRD) {
4942  if (D->isImplicit())
4943  continue;
4944  return {NonCLikeKind::OtherMember, D->getSourceRange()};
4945  }
4946 
4947  // -- contain a lambda-expression,
4948  if (MemberRD->isLambda())
4949  return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4950 
4951  // and all member classes shall also satisfy these requirements
4952  // (recursively).
4953  if (MemberRD->isThisDeclarationADefinition()) {
4954  if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4955  return Kind;
4956  }
4957  }
4958 
4959  return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4960 }
4961 
4963  TypedefNameDecl *NewTD) {
4964  if (TagFromDeclSpec->isInvalidDecl())
4965  return;
4966 
4967  // Do nothing if the tag already has a name for linkage purposes.
4968  if (TagFromDeclSpec->hasNameForLinkage())
4969  return;
4970 
4971  // A well-formed anonymous tag must always be a TUK_Definition.
4972  assert(TagFromDeclSpec->isThisDeclarationADefinition());
4973 
4974  // The type must match the tag exactly; no qualifiers allowed.
4975  if (!Context.hasSameType(NewTD->getUnderlyingType(),
4976  Context.getTagDeclType(TagFromDeclSpec))) {
4977  if (getLangOpts().CPlusPlus)
4978  Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4979  return;
4980  }
4981 
4982  // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4983  // An unnamed class with a typedef name for linkage purposes shall [be
4984  // C-like].
4985  //
4986  // FIXME: Also diagnose if we've already computed the linkage. That ideally
4987  // shouldn't happen, but there are constructs that the language rule doesn't
4988  // disallow for which we can't reasonably avoid computing linkage early.
4989  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4990  NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4991  : NonCLikeKind();
4992  bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4993  if (NonCLike || ChangesLinkage) {
4994  if (NonCLike.Kind == NonCLikeKind::Invalid)
4995  return;
4996 
4997  unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4998  if (ChangesLinkage) {
4999  // If the linkage changes, we can't accept this as an extension.
5000  if (NonCLike.Kind == NonCLikeKind::None)
5001  DiagID = diag::err_typedef_changes_linkage;
5002  else
5003  DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5004  }
5005 
5006  SourceLocation FixitLoc =
5007  getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5008  llvm::SmallString<40> TextToInsert;
5009  TextToInsert += ' ';
5010  TextToInsert += NewTD->getIdentifier()->getName();
5011 
5012  Diag(FixitLoc, DiagID)
5013  << isa<TypeAliasDecl>(NewTD)
5014  << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5015  if (NonCLike.Kind != NonCLikeKind::None) {
5016  Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5017  << NonCLike.Kind - 1 << NonCLike.Range;
5018  }
5019  Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5020  << NewTD << isa<TypeAliasDecl>(NewTD);
5021 
5022  if (ChangesLinkage)
5023  return;
5024  }
5025 
5026  // Otherwise, set this as the anon-decl typedef for the tag.
5027  TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5028 }
5029 
5031  switch (T) {
5032  case DeclSpec::TST_class:
5033  return 0;
5034  case DeclSpec::TST_struct:
5035  return 1;
5037  return 2;
5038  case DeclSpec::TST_union:
5039  return 3;
5040  case DeclSpec::TST_enum:
5041  return 4;
5042  default:
5043  llvm_unreachable("unexpected type specifier");
5044  }
5045 }
5046 
5047 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
5048 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
5049 /// parameters to cope with template friend declarations.
5051  DeclSpec &DS,
5052  const ParsedAttributesView &DeclAttrs,
5053  MultiTemplateParamsArg TemplateParams,
5054  bool IsExplicitInstantiation,
5055  RecordDecl *&AnonRecord) {
5056  Decl *TagD = nullptr;
5057  TagDecl *Tag = nullptr;
5058  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5063  TagD = DS.getRepAsDecl();
5064 
5065  if (!TagD) // We probably had an error
5066  return nullptr;
5067 
5068  // Note that the above type specs guarantee that the
5069  // type rep is a Decl, whereas in many of the others
5070  // it's a Type.
5071  if (isa<TagDecl>(TagD))
5072  Tag = cast<TagDecl>(TagD);
5073  else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5074  Tag = CTD->getTemplatedDecl();
5075  }
5076 
5077  if (Tag) {
5078  handleTagNumbering(Tag, S);
5079  Tag->setFreeStanding();
5080  if (Tag->isInvalidDecl())
5081  return Tag;
5082  }
5083 
5084  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5085  // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5086  // or incomplete types shall not be restrict-qualified."
5087  if (TypeQuals & DeclSpec::TQ_restrict)
5088  Diag(DS.getRestrictSpecLoc(),
5089  diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5090  << DS.getSourceRange();
5091  }
5092 
5093  if (DS.isInlineSpecified())
5094  Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5095  << getLangOpts().CPlusPlus17;
5096 
5097  if (DS.hasConstexprSpecifier()) {
5098  // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5099  // and definitions of functions and variables.
5100  // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5101  // the declaration of a function or function template
5102  if (Tag)
5103  Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5105  << static_cast<int>(DS.getConstexprSpecifier());
5106  else
5107  Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5108  << static_cast<int>(DS.getConstexprSpecifier());
5109  // Don't emit warnings after this error.
5110  return TagD;
5111  }
5112 
5113  DiagnoseFunctionSpecifiers(DS);
5114 
5115  if (DS.isFriendSpecified()) {
5116  // If we're dealing with a decl but not a TagDecl, assume that
5117  // whatever routines created it handled the friendship aspect.
5118  if (TagD && !Tag)
5119  return nullptr;
5120  return ActOnFriendTypeDecl(S, DS, TemplateParams);
5121  }
5122 
5123  const CXXScopeSpec &SS = DS.getTypeSpecScope();
5124  bool IsExplicitSpecialization =
5125  !TemplateParams.empty() && TemplateParams.back()->size() == 0;
5126  if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
5127  !IsExplicitInstantiation && !IsExplicitSpecialization &&
5128  !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
5129  // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
5130  // nested-name-specifier unless it is an explicit instantiation
5131  // or an explicit specialization.
5132  //
5133  // FIXME: We allow class template partial specializations here too, per the
5134  // obvious intent of DR1819.
5135  //
5136  // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
5137  Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
5139  return nullptr;
5140  }
5141 
5142  // Track whether this decl-specifier declares anything.
5143  bool DeclaresAnything = true;
5144 
5145  // Handle anonymous struct definitions.
5146  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5147  if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5149  if (getLangOpts().CPlusPlus ||
5150  Record->getDeclContext()->isRecord()) {
5151  // If CurContext is a DeclContext that can contain statements,
5152  // RecursiveASTVisitor won't visit the decls that
5153  // BuildAnonymousStructOrUnion() will put into CurContext.
5154  // Also store them here so that they can be part of the
5155  // DeclStmt that gets created in this case.
5156  // FIXME: Also return the IndirectFieldDecls created by
5157  // BuildAnonymousStructOr union, for the same reason?
5158  if (CurContext->isFunctionOrMethod())
5159  AnonRecord = Record;
5160  return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5161  Context.getPrintingPolicy());
5162  }
5163 
5164  DeclaresAnything = false;
5165  }
5166  }
5167 
5168  // C11 6.7.2.1p2:
5169  // A struct-declaration that does not declare an anonymous structure or
5170  // anonymous union shall contain a struct-declarator-list.
5171  //
5172  // This rule also existed in C89 and C99; the grammar for struct-declaration
5173  // did not permit a struct-declaration without a struct-declarator-list.
5174  if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5176  // Check for Microsoft C extension: anonymous struct/union member.
5177  // Handle 2 kinds of anonymous struct/union:
5178  // struct STRUCT;
5179  // union UNION;
5180  // and
5181  // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5182  // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5183  if ((Tag && Tag->getDeclName()) ||
5185  RecordDecl *Record = nullptr;
5186  if (Tag)
5187  Record = dyn_cast<RecordDecl>(Tag);
5188  else if (const RecordType *RT =
5190  Record = RT->getDecl();
5191  else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5192  Record = UT->getDecl();
5193 
5194  if (Record && getLangOpts().MicrosoftExt) {
5195  Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5196  << Record->isUnion() << DS.getSourceRange();
5197  return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5198  }
5199 
5200  DeclaresAnything = false;
5201  }
5202  }
5203 
5204  // Skip all the checks below if we have a type error.
5205  if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5206  (TagD && TagD->isInvalidDecl()))
5207  return TagD;
5208 
5209  if (getLangOpts().CPlusPlus &&
5211  if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5212  if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5213  !Enum->getIdentifier() && !Enum->isInvalidDecl())
5214  DeclaresAnything = false;
5215 
5216  if (!DS.isMissingDeclaratorOk()) {
5217  // Customize diagnostic for a typedef missing a name.
5219  Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5220  << DS.getSourceRange();
5221  else
5222  DeclaresAnything = false;
5223  }
5224 
5225  if (DS.isModulePrivateSpecified() &&
5226  Tag && Tag->getDeclContext()->isFunctionOrMethod())
5227  Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5228  << Tag->getTagKind()
5230 
5231  ActOnDocumentableDecl(TagD);
5232 
5233  // C 6.7/2:
5234  // A declaration [...] shall declare at least a declarator [...], a tag,
5235  // or the members of an enumeration.
5236  // C++ [dcl.dcl]p3:
5237  // [If there are no declarators], and except for the declaration of an
5238  // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5239  // names into the program, or shall redeclare a name introduced by a
5240  // previous declaration.
5241  if (!DeclaresAnything) {
5242  // In C, we allow this as a (popular) extension / bug. Don't bother
5243  // producing further diagnostics for redundant qualifiers after this.
5244  Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5245  ? diag::err_no_declarators
5246  : diag::ext_no_declarators)
5247  << DS.getSourceRange();
5248  return TagD;
5249  }
5250 
5251  // C++ [dcl.stc]p1:
5252  // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5253  // init-declarator-list of the declaration shall not be empty.
5254  // C++ [dcl.fct.spec]p1:
5255  // If a cv-qualifier appears in a decl-specifier-seq, the
5256  // init-declarator-list of the declaration shall not be empty.
5257  //
5258  // Spurious qualifiers here appear to be valid in C.
5259  unsigned DiagID = diag::warn_standalone_specifier;
5260  if (getLangOpts().CPlusPlus)
5261  DiagID = diag::ext_standalone_specifier;
5262 
5263  // Note that a linkage-specification sets a storage class, but
5264  // 'extern "C" struct foo;' is actually valid and not theoretically
5265  // useless.
5266  if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5267  if (SCS == DeclSpec::SCS_mutable)
5268  // Since mutable is not a viable storage class specifier in C, there is
5269  // no reason to treat it as an extension. Instead, diagnose as an error.
5270  Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5271  else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5272  Diag(DS.getStorageClassSpecLoc(), DiagID)
5274  }
5275 
5276  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5277  Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5278  << DeclSpec::getSpecifierName(TSCS);
5279  if (DS.getTypeQualifiers()) {
5281  Diag(DS.getConstSpecLoc(), DiagID) << "const";
5283  Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5284  // Restrict is covered above.
5286  Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5288  Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5289  }
5290 
5291  // Warn about ignored type attributes, for example:
5292  // __attribute__((aligned)) struct A;
5293  // Attributes should be placed after tag to apply to type declaration.
5294  if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5295  DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5296  if (TypeSpecType == DeclSpec::TST_class ||
5297  TypeSpecType == DeclSpec::TST_struct ||
5298  TypeSpecType == DeclSpec::TST_interface ||
5299  TypeSpecType == DeclSpec::TST_union ||
5300  TypeSpecType == DeclSpec::TST_enum) {
5301  for (const ParsedAttr &AL : DS.getAttributes())
5302  Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5303  << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5304  for (const ParsedAttr &AL : DeclAttrs)
5305  Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5306  << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5307  }
5308  }
5309 
5310  return TagD;
5311 }
5312 
5313 /// We are trying to inject an anonymous member into the given scope;
5314 /// check if there's an existing declaration that can't be overloaded.
5315 ///
5316 /// \return true if this is a forbidden redeclaration
5317 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5318  Scope *S,
5319  DeclContext *Owner,
5320  DeclarationName Name,
5321  SourceLocation NameLoc,
5322  bool IsUnion) {
5323  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5325  if (!SemaRef.LookupName(R, S)) return false;
5326 
5327  // Pick a representative declaration.
5329  assert(PrevDecl && "Expected a non-null Decl");
5330 
5331  if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5332  return false;
5333 
5334  SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5335  << IsUnion << Name;
5336  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5337 
5338  return true;
5339 }
5340 
5341 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5342 /// anonymous struct or union AnonRecord into the owning context Owner
5343 /// and scope S. This routine will be invoked just after we realize
5344 /// that an unnamed union or struct is actually an anonymous union or
5345 /// struct, e.g.,
5346 ///
5347 /// @code
5348 /// union {
5349 /// int i;
5350 /// float f;
5351 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5352 /// // f into the surrounding scope.x
5353 /// @endcode
5354 ///
5355 /// This routine is recursive, injecting the names of nested anonymous
5356 /// structs/unions into the owning context and scope as well.
5357 static bool
5359  RecordDecl *AnonRecord, AccessSpecifier AS,
5360  SmallVectorImpl<NamedDecl *> &Chaining) {
5361  bool Invalid = false;
5362 
5363  // Look every FieldDecl and IndirectFieldDecl with a name.
5364  for (auto *D : AnonRecord->decls()) {
5365  if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5366  cast<NamedDecl>(D)->getDeclName()) {
5367  ValueDecl *VD = cast<ValueDecl>(D);
5368  if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5369  VD->getLocation(),
5370  AnonRecord->isUnion())) {
5371  // C++ [class.union]p2:
5372  // The names of the members of an anonymous union shall be
5373  // distinct from the names of any other entity in the
5374  // scope in which the anonymous union is declared.
5375  Invalid = true;
5376  } else {
5377  // C++ [class.union]p2:
5378  // For the purpose of name lookup, after the anonymous union
5379  // definition, the members of the anonymous union are
5380  // considered to have been defined in the scope in which the
5381  // anonymous union is declared.
5382  unsigned OldChainingSize = Chaining.size();
5383  if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5384  Chaining.append(IF->chain_begin(), IF->chain_end());
5385  else
5386  Chaining.push_back(VD);
5387 
5388  assert(Chaining.size() >= 2);
5389  NamedDecl **NamedChain =
5390  new (SemaRef.Context)NamedDecl*[Chaining.size()];
5391  for (unsigned i = 0; i < Chaining.size(); i++)
5392  NamedChain[i] = Chaining[i];
5393 
5395  SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5396  VD->getType(), {NamedChain, Chaining.size()});
5397 
5398  for (const auto *Attr : VD->attrs())
5399  IndirectField->addAttr(Attr->clone(SemaRef.Context));
5400 
5401  IndirectField->setAccess(AS);
5402  IndirectField->setImplicit();
5403  SemaRef.PushOnScopeChains(IndirectField, S);
5404 
5405  // That includes picking up the appropriate access specifier.
5406  if (AS != AS_none) IndirectField->setAccess(AS);
5407 
5408  Chaining.resize(OldChainingSize);
5409  }
5410  }
5411  }
5412 
5413  return Invalid;
5414 }
5415 
5416 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5417 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5418 /// illegal input values are mapped to SC_None.
5419 static StorageClass
5421  DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5422  assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5423  "Parser allowed 'typedef' as storage class VarDecl.");
5424  switch (StorageClassSpec) {
5425  case DeclSpec::SCS_unspecified: return SC_None;
5426  case DeclSpec::SCS_extern:
5427  if (DS.isExternInLinkageSpec())
5428  return SC_None;
5429  return SC_Extern;
5430  case DeclSpec::SCS_static: return SC_Static;
5431  case DeclSpec::SCS_auto: return SC_Auto;
5432  case DeclSpec::SCS_register: return SC_Register;
5434  // Illegal SCSs map to None: error reporting is up to the caller.
5435  case DeclSpec::SCS_mutable: // Fall through.
5436  case DeclSpec::SCS_typedef: return SC_None;
5437  }
5438  llvm_unreachable("unknown storage class specifier");
5439 }
5440 
5442  assert(Record->hasInClassInitializer());
5443 
5444  for (const auto *I : Record->decls()) {
5445  const auto *FD = dyn_cast<FieldDecl>(I);
5446  if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5447  FD = IFD->getAnonField();
5448  if (FD && FD->hasInClassInitializer())
5449  return FD->getLocation();
5450  }
5451 
5452  llvm_unreachable("couldn't find in-class initializer");
5453 }
5454 
5456  SourceLocation DefaultInitLoc) {
5457  if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5458  return;
5459 
5460  S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5461  S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5462 }
5463 
5465  CXXRecordDecl *AnonUnion) {
5466  if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5467  return;
5468 
5470 }
5471 
5472 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5473 /// anonymous structure or union. Anonymous unions are a C++ feature
5474 /// (C++ [class.union]) and a C11 feature; anonymous structures
5475 /// are a C11 feature and GNU C++ extension.
5477  AccessSpecifier AS,
5478  RecordDecl *Record,
5479  const PrintingPolicy &Policy) {
5480  DeclContext *Owner = Record->getDeclContext();
5481 
5482  // Diagnose whether this anonymous struct/union is an extension.
5483  if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5484  Diag(Record->getLocation(), diag::ext_anonymous_union);
5485  else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5486  Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5487  else if (!Record->isUnion() && !getLangOpts().C11)
5488  Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5489 
5490  // C and C++ require different kinds of checks for anonymous
5491  // structs/unions.
5492  bool Invalid = false;
5493  if (getLangOpts().CPlusPlus) {
5494  const char *PrevSpec = nullptr;
5495  if (Record->isUnion()) {
5496  // C++ [class.union]p6:
5497  // C++17 [class.union.anon]p2:
5498  // Anonymous unions declared in a named namespace or in the
5499  // global namespace shall be declared static.
5500  unsigned DiagID;
5501  DeclContext *OwnerScope = Owner->getRedeclContext();
5503  (OwnerScope->isTranslationUnit() ||
5504  (OwnerScope->isNamespace() &&
5505  !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5506  Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5507  << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5508 
5509  // Recover by adding 'static'.
5511  PrevSpec, DiagID, Policy);
5512  }
5513  // C++ [class.union]p6:
5514  // A storage class is not allowed in a declaration of an
5515  // anonymous union in a class scope.
5517  isa<RecordDecl>(Owner)) {
5519  diag::err_anonymous_union_with_storage_spec)
5521 
5522  // Recover by removing the storage specifier.
5524  SourceLocation(),
5525  PrevSpec, DiagID, Context.getPrintingPolicy());
5526  }
5527  }
5528 
5529  // Ignore const/volatile/restrict qualifiers.
5530  if (DS.getTypeQualifiers()) {
5532  Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5533  << Record->isUnion() << "const"
5536  Diag(DS.getVolatileSpecLoc(),
5537  diag::ext_anonymous_struct_union_qualified)
5538  << Record->isUnion() << "volatile"
5541  Diag(DS.getRestrictSpecLoc(),
5542  diag::ext_anonymous_struct_union_qualified)
5543  << Record->isUnion() << "restrict"
5546  Diag(DS.getAtomicSpecLoc(),
5547  diag::ext_anonymous_struct_union_qualified)
5548  << Record->isUnion() << "_Atomic"
5552  diag::ext_anonymous_struct_union_qualified)
5553  << Record->isUnion() << "__unaligned"
5555 
5556  DS.ClearTypeQualifiers();
5557  }
5558 
5559  // C++ [class.union]p2:
5560  // The member-specification of an anonymous union shall only
5561  // define non-static data members. [Note: nested types and
5562  // functions cannot be declared within an anonymous union. ]
5563  for (auto *Mem : Record->decls()) {
5564  // Ignore invalid declarations; we already diagnosed them.
5565  if (Mem->isInvalidDecl())
5566  continue;
5567 
5568  if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5569  // C++ [class.union]p3:
5570  // An anonymous union shall not have private or protected
5571  // members (clause 11).
5572  assert(FD->getAccess() != AS_none);
5573  if (FD->getAccess() != AS_public) {
5574  Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5575  << Record->isUnion() << (FD->getAccess() == AS_protected);
5576  Invalid = true;
5577  }
5578 
5579  // C++ [class.union]p1
5580  // An object of a class with a non-trivial constructor, a non-trivial
5581  // copy constructor, a non-trivial destructor, or a non-trivial copy
5582  // assignment operator cannot be a member of a union, nor can an
5583  // array of such objects.
5584  if (CheckNontrivialField(FD))
5585  Invalid = true;
5586  } else if (Mem->isImplicit()) {
5587  // Any implicit members are fine.
5588  } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5589  // This is a type that showed up in an
5590  // elaborated-type-specifier inside the anonymous struct or
5591  // union, but which actually declares a type outside of the
5592  // anonymous struct or union. It's okay.
5593  } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5594  if (!MemRecord->isAnonymousStructOrUnion() &&
5595  MemRecord->getDeclName()) {
5596  // Visual C++ allows type definition in anonymous struct or union.
5597  if (getLangOpts().MicrosoftExt)
5598  Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5599  << Record->isUnion();
5600  else {
5601  // This is a nested type declaration.
5602  Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5603  << Record->isUnion();
5604  Invalid = true;
5605  }
5606  } else {
5607  // This is an anonymous type definition within another anonymous type.
5608  // This is a popular extension, provided by Plan9, MSVC and GCC, but
5609  // not part of standard C++.
5610  Diag(MemRecord->getLocation(),
5611  diag::ext_anonymous_record_with_anonymous_type)
5612  << Record->isUnion();
5613  }
5614  } else if (isa<AccessSpecDecl>(Mem)) {
5615  // Any access specifier is fine.
5616  } else if (isa<StaticAssertDecl>(Mem)) {
5617  // In C++1z, static_assert declarations are also fine.
5618  } else {
5619  // We have something that isn't a non-static data
5620  // member. Complain about it.
5621  unsigned DK = diag::err_anonymous_record_bad_member;
5622  if (isa<TypeDecl>(Mem))
5623  DK = diag::err_anonymous_record_with_type;
5624  else if (isa<FunctionDecl>(Mem))
5625  DK = diag::err_anonymous_record_with_function;
5626  else if (isa<VarDecl>(Mem))
5627  DK = diag::err_anonymous_record_with_static;
5628 
5629  // Visual C++ allows type definition in anonymous struct or union.
5630  if (getLangOpts().MicrosoftExt &&
5631  DK == diag::err_anonymous_record_with_type)
5632  Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5633  << Record->isUnion();
5634  else {
5635  Diag(Mem->getLocation(), DK) << Record->isUnion();
5636  Invalid = true;
5637  }
5638  }
5639  }
5640 
5641  // C++11 [class.union]p8 (DR1460):
5642  // At most one variant member of a union may have a
5643  // brace-or-equal-initializer.
5644  if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5645  Owner->isRecord())
5646  checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5647  cast<CXXRecordDecl>(Record));
5648  }
5649 
5650  if (!Record->isUnion() && !Owner->isRecord()) {
5651  Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5652  << getLangOpts().CPlusPlus;
5653  Invalid = true;
5654  }
5655 
5656  // C++ [dcl.dcl]p3:
5657  // [If there are no declarators], and except for the declaration of an
5658  // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5659  // names into the program
5660  // C++ [class.mem]p2:
5661  // each such member-declaration shall either declare at least one member
5662  // name of the class or declare at least one unnamed bit-field
5663  //
5664  // For C this is an error even for a named struct, and is diagnosed elsewhere.
5665  if (getLangOpts().CPlusPlus && Record->field_empty())
5666  Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5667 
5668  // Mock up a declarator.
5670  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5671  assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5672 
5673  // Create a declaration for this anonymous struct/union.
5674  NamedDecl *Anon = nullptr;
5675  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5676  Anon = FieldDecl::Create(
5677  Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5678  /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5679  /*BitWidth=*/nullptr, /*Mutable=*/false,
5680  /*InitStyle=*/ICIS_NoInit);
5681  Anon->setAccess(AS);
5682  ProcessDeclAttributes(S, Anon, Dc);
5683 
5684  if (getLangOpts().CPlusPlus)
5685  FieldCollector->Add(cast<FieldDecl>(Anon));
5686  } else {
5687  DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5689  if (SCSpec == DeclSpec::SCS_mutable) {
5690  // mutable can only appear on non-static class members, so it's always
5691  // an error here
5692  Diag(Record->getLocation(), diag::err_mutable_nonmember);
5693  Invalid = true;
5694  SC = SC_None;
5695  }
5696 
5697  assert(DS.getAttributes().empty() && "No attribute expected");
5698  Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5699  Record->getLocation(), /*IdentifierInfo=*/nullptr,
5700  Context.getTypeDeclType(Record), TInfo, SC);
5701 
5702  // Default-initialize the implicit variable. This initialization will be
5703  // trivial in almost all cases, except if a union member has an in-class
5704  // initializer:
5705  // union { int n = 0; };
5706  ActOnUninitializedDecl(Anon);
5707  }
5708  Anon->setImplicit();
5709 
5710  // Mark this as an anonymous struct/union type.
5711  Record->setAnonymousStructOrUnion(true);
5712 
5713  // Add the anonymous struct/union object to the current
5714  // context. We'll be referencing this object when we refer to one of
5715  // its members.
5716  Owner->addDecl(Anon);
5717 
5718  // Inject the members of the anonymous struct/union into the owning
5719  // context and into the identifier resolver chain for name lookup
5720  // purposes.
5722  Chain.push_back(Anon);
5723 
5724  if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5725  Invalid = true;
5726 
5727  if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5728  if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5729  MangleNumberingContext *MCtx;
5730  Decl *ManglingContextDecl;
5731  std::tie(MCtx, ManglingContextDecl) =
5732  getCurrentMangleNumberContext(NewVD->getDeclContext());
5733  if (MCtx) {
5734  Context.setManglingNumber(
5735  NewVD, MCtx->getManglingNumber(
5736  NewVD, getMSManglingNumber(getLangOpts(), S)));
5737  Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5738  }
5739  }
5740  }
5741 
5742  if (Invalid)
5743  Anon->setInvalidDecl();
5744 
5745  return Anon;
5746 }
5747 
5748 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5749 /// Microsoft C anonymous structure.
5750 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5751 /// Example:
5752 ///
5753 /// struct A { int a; };
5754 /// struct B { struct A; int b; };
5755 ///
5756 /// void foo() {
5757 /// B var;
5758 /// var.a = 3;
5759 /// }
5760 ///
5762  RecordDecl *Record) {
5763  assert(Record && "expected a record!");
5764 
5765  // Mock up a declarator.
5767  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5768  assert(TInfo && "couldn't build declarator info for anonymous struct");
5769 
5770  auto *ParentDecl = cast<RecordDecl>(CurContext);
5771  QualType RecTy = Context.getTypeDeclType(Record);
5772 
5773  // Create a declaration for this anonymous struct.
5774  NamedDecl *Anon =
5775  FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5776  /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5777  /*BitWidth=*/nullptr, /*Mutable=*/false,
5778  /*InitStyle=*/ICIS_NoInit);
5779  Anon->setImplicit();
5780 
5781  // Add the anonymous struct object to the current context.
5782  CurContext->addDecl(Anon);
5783 
5784  // Inject the members of the anonymous struct into the current
5785  // context and into the identifier resolver chain for name lookup
5786  // purposes.
5788  Chain.push_back(Anon);
5789 
5790  RecordDecl *RecordDef = Record->getDefinition();
5791  if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5792  diag::err_field_incomplete_or_sizeless) ||
5793  InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5794  AS_none, Chain)) {
5795  Anon->setInvalidDecl();
5796  ParentDecl->setInvalidDecl();
5797  }
5798 
5799  return Anon;
5800 }
5801 
5802 /// GetNameForDeclarator - Determine the full declaration name for the
5803 /// given Declarator.
5805  return GetNameFromUnqualifiedId(D.getName());
5806 }
5807 
5808 /// Retrieves the declaration name from a parsed unqualified-id.
5811  DeclarationNameInfo NameInfo;
5812  NameInfo.setLoc(Name.StartLocation);
5813 
5814  switch (Name.getKind()) {
5815 
5818  NameInfo.setName(Name.Identifier);
5819  return NameInfo;
5820 
5822  // C++ [temp.deduct.guide]p3:
5823  // The simple-template-id shall name a class template specialization.
5824  // The template-name shall be the same identifier as the template-name
5825  // of the simple-template-id.
5826  // These together intend to imply that the template-name shall name a
5827  // class template.
5828  // FIXME: template<typename T> struct X {};
5829  // template<typename T> using Y = X<T>;
5830  // Y(int) -> Y<int>;
5831  // satisfies these rules but does not name a class template.
5832  TemplateName TN = Name.TemplateName.get().get();
5833  auto *Template = TN.getAsTemplateDecl();
5834  if (!Template || !isa<ClassTemplateDecl>(Template)) {
5835  Diag(Name.StartLocation,
5836  diag::err_deduction_guide_name_not_class_template)
5837  << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5838  if (Template)
5839  Diag(Template->getLocation(), diag::note_template_decl_here);
5840  return DeclarationNameInfo();
5841  }
5842 
5843  NameInfo.setName(
5844  Context.DeclarationNames.getCXXDeductionGuideName(Template));
5845  return NameInfo;
5846  }
5847 
5849  NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5850  Name.OperatorFunctionId.Operator));
5852  Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5853  return NameInfo;
5854 
5857  Name.Identifier));
5858  NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5859  return NameInfo;
5860 
5862  TypeSourceInfo *TInfo;
5863  QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5864  if (Ty.isNull())
5865  return DeclarationNameInfo();
5867  Context.getCanonicalType(Ty)));
5868  NameInfo.setNamedTypeInfo(TInfo);
5869  return NameInfo;
5870  }
5871 
5873  TypeSourceInfo *TInfo;
5874  QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5875  if (Ty.isNull())
5876  return DeclarationNameInfo();
5878  Context.getCanonicalType(Ty)));
5879  NameInfo.setNamedTypeInfo(TInfo);
5880  return NameInfo;
5881  }
5882 
5884  // In well-formed code, we can only have a constructor
5885  // template-id that refers to the current context, so go there
5886  // to find the actual type being constructed.
5887  CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5888  if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5889  return DeclarationNameInfo();
5890 
5891  // Determine the type of the class being constructed.
5892  QualType CurClassType = Context.getTypeDeclType(CurClass);
5893 
5894  // FIXME: Check two things: that the template-id names the same type as
5895  // CurClassType, and that the template-id does not occur when the name
5896  // was qualified.
5897 
5899  Context.getCanonicalType(CurClassType)));
5900  // FIXME: should we retrieve TypeSourceInfo?
5901  NameInfo.setNamedTypeInfo(nullptr);
5902  return NameInfo;
5903  }
5904 
5906  TypeSourceInfo *TInfo;
5907  QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5908  if (Ty.isNull())
5909  return DeclarationNameInfo();
5911  Context.getCanonicalType(Ty)));
5912  NameInfo.setNamedTypeInfo(TInfo);
5913  return NameInfo;
5914  }
5915 
5917  TemplateName TName = Name.TemplateId->Template.get();
5918  SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5919  return Context.getNameForTemplate(TName, TNameLoc);
5920  }
5921 
5922  } // switch (Name.getKind())
5923 
5924  llvm_unreachable("Unknown name kind");
5925 }
5926 
5928  do {
5929  if (Ty->isPointerType() || Ty->isReferenceType())
5930  Ty = Ty->getPointeeType();
5931  else if (Ty->isArrayType())
5932  Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5933  else
5934  return Ty.withoutLocalFastQualifiers();
5935  } while (true);
5936 }
5937 
5938 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5939 /// and Definition have "nearly" matching parameters. This heuristic is
5940 /// used to improve diagnostics in the case where an out-of-line function
5941 /// definition doesn't match any declaration within the class or namespace.
5942 /// Also sets Params to the list of indices to the parameters that differ
5943 /// between the declaration and the definition. If hasSimilarParameters
5944 /// returns true and Params is empty, then all of the parameters match.
5945 static bool hasSimilarParameters(ASTContext &Context,
5946  FunctionDecl *Declaration,
5947  FunctionDecl *Definition,
5948  SmallVectorImpl<unsigned> &Params) {
5949  Params.clear();
5950  if (Declaration->param_size() != Definition->param_size())
5951  return false;
5952  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5953  QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5954  QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5955 
5956  // The parameter types are identical
5957  if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5958  continue;
5959 
5960  QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5961  QualType DefParamBaseTy = getCoreType(DefParamTy);
5962  const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5963  const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5964 
5965  if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5966  (DeclTyName && DeclTyName == DefTyName))
5967  Params.push_back(Idx);
5968  else // The two parameters aren't even close
5969  return false;
5970  }
5971 
5972  return true;
5973 }
5974 
5975 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5976 /// declarator needs to be rebuilt in the current instantiation.
5977 /// Any bits of declarator which appear before the name are valid for
5978 /// consideration here. That's specifically the type in the decl spec
5979 /// and the base type in any member-pointer chunks.
5981  DeclarationName Name) {
5982  // The types we specifically need to rebuild are:
5983  // - typenames, typeofs, and decltypes
5984  // - types which will become injected class names
5985  // Of course, we also need to rebuild any type referencing such a
5986  // type. It's safest to just say "dependent", but we call out a
5987  // few cases here.
5988 
5989  DeclSpec &DS = D.getMutableDeclSpec();
5990  switch (DS.getTypeSpecType()) {
5994 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
5995 #include "clang/Basic/TransformTypeTraits.def"
5996  case DeclSpec::TST_atomic: {
5997  // Grab the type from the parser.
5998  TypeSourceInfo *TSI = nullptr;
5999  QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6000  if (T.isNull() || !T->isInstantiationDependentType()) break;
6001 
6002  // Make sure there's a type source info. This isn't really much
6003  // of a waste; most dependent types should have type source info
6004  // attached already.
6005  if (!TSI)
6007 
6008  // Rebuild the type in the current instantiation.
6009  TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
6010  if (!TSI) return true;
6011 
6012  // Store the new type back in the decl spec.
6013  ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6014  DS.UpdateTypeRep(LocType);
6015  break;
6016  }
6017 
6020  case DeclSpec::TST_typeofExpr: {
6021  Expr *E = DS.getRepAsExpr();
6023  if (Result.isInvalid()) return true;
6024  DS.UpdateExprRep(Result.get());
6025  break;
6026  }
6027 
6028  default:
6029  // Nothing to do for these decl specs.
6030  break;
6031  }
6032 
6033  // It doesn't matter what order we do this in.
6034  for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6035  DeclaratorChunk &Chunk = D.getTypeObject(I);
6036 
6037  // The only type information in the declarator which can come
6038  // before the declaration name is the base type of a member
6039  // pointer.
6040  if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6041  continue;
6042 
6043  // Rebuild the scope specifier in-place.
6044  CXXScopeSpec &SS = Chunk.Mem.Scope();
6046  return true;
6047  }
6048 
6049  return false;
6050 }
6051 
6052 /// Returns true if the declaration is declared in a system header or from a
6053 /// system macro.
6054 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6055  return SM.isInSystemHeader(D->getLocation()) ||
6056  SM.isInSystemMacro(D->getLocation());
6057 }
6058 
6060  // Avoid warning twice on the same identifier, and don't warn on redeclaration
6061  // of system decl.
6062  if (D->getPreviousDecl() || D->isImplicit())
6063  return;
6064  ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6065  if (Status != ReservedIdentifierStatus::NotReserved &&
6066  !isFromSystemHeader(Context.getSourceManager(), D)) {
6067  Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6068  << D << static_cast<int>(Status);
6069  }
6070 }
6071 
6074 
6075  // Check if we are in an `omp begin/end declare variant` scope. Handle this
6076  // declaration only if the `bind_to_declaration` extension is set.
6078  if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
6079  if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
6080  implementation_extension_bind_to_declaration))
6081  ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6082  S, D, MultiTemplateParamsArg(), Bases);
6083 
6084  Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
6085 
6086  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6087  Dcl && Dcl->getDeclContext()->isFileContext())
6089 
6090  if (!Bases.empty())
6091  ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
6092 
6093  return Dcl;
6094 }
6095 
6096 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
6097 /// If T is the name of a class, then each of the following shall have a
6098 /// name different from T:
6099 /// - every static data member of class T;
6100 /// - every member function of class T
6101 /// - every member of class T that is itself a type;
6102 /// \returns true if the declaration name violates these rules.
6104  DeclarationNameInfo NameInfo) {
6105  DeclarationName Name = NameInfo.getName();
6106 
6107  CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6108  while (Record && Record->isAnonymousStructOrUnion())
6109  Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6110  if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6111  Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6112  return true;
6113  }
6114 
6115  return false;
6116 }
6117 
6118 /// Diagnose a declaration whose declarator-id has the given
6119 /// nested-name-specifier.
6120 ///
6121 /// \param SS The nested-name-specifier of the declarator-id.
6122 ///
6123 /// \param DC The declaration context to which the nested-name-specifier
6124 /// resolves.
6125 ///
6126 /// \param Name The name of the entity being declared.
6127 ///
6128 /// \param Loc The location of the name of the entity being declared.
6129 ///
6130 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
6131 /// we're declaring an explicit / partial specialization / instantiation.
6132 ///
6133 /// \returns true if we cannot safely recover from this error, false otherwise.
6135  DeclarationName Name,
6136  SourceLocation Loc, bool IsTemplateId) {
6137  DeclContext *Cur = CurContext;
6138  while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6139  Cur = Cur->getParent();
6140 
6141  // If the user provided a superfluous scope specifier that refers back to the
6142  // class in which the entity is already declared, diagnose and ignore it.
6143  //
6144  // class X {
6145  // void X::f();
6146  // };
6147  //
6148  // Note, it was once ill-formed to give redundant qualification in all
6149  // contexts, but that rule was removed by DR482.
6150  if (Cur->Equals(DC)) {
6151  if (Cur->isRecord()) {
6152  Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6153  : diag::err_member_extra_qualification)
6154  << Name << FixItHint::CreateRemoval(SS.getRange());
6155  SS.clear();
6156  } else {
6157  Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6158  }
6159  return false;
6160  }
6161 
6162  // Check whether the qualifying scope encloses the scope of the original
6163  // declaration. For a template-id, we perform the checks in
6164  // CheckTemplateSpecializationScope.
6165  if (!Cur->Encloses(DC) && !IsTemplateId) {
6166  if (Cur->isRecord())
6167  Diag(Loc, diag::err_member_qualification)
6168  << Name << SS.getRange();
6169  else if (isa<TranslationUnitDecl>(DC))
6170  Diag(Loc, diag::err_invalid_declarator_global_scope)
6171  << Name << SS.getRange();
6172  else if (isa<FunctionDecl>(Cur))
6173  Diag(Loc, diag::err_invalid_declarator_in_function)
6174  << Name << SS.getRange();
6175  else if (isa<BlockDecl>(Cur))
6176  Diag(Loc, diag::err_invalid_declarator_in_block)
6177  << Name << SS.getRange();
6178  else if (isa<ExportDecl>(Cur)) {
6179  if (!isa<NamespaceDecl>(DC))
6180  Diag(Loc, diag::err_export_non_namespace_scope_name)
6181  << Name << SS.getRange();
6182  else
6183  // The cases that DC is not NamespaceDecl should be handled in
6184  // CheckRedeclarationExported.
6185  return false;
6186  } else
6187  Diag(Loc, diag::err_invalid_declarator_scope)
6188  << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6189 
6190  return true;
6191  }
6192 
6193  if (Cur->isRecord()) {
6194  // Cannot qualify members within a class.
6195  Diag(Loc, diag::err_member_qualification)
6196  << Name << SS.getRange();
6197  SS.clear();
6198 
6199  // C++ constructors and destructors with incorrect scopes can break
6200  // our AST invariants by having the wrong underlying types. If
6201  // that's the case, then drop this declaration entirely.
6202  if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6203  Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6204  !Context.hasSameType(Name.getCXXNameType(),
6205  Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6206  return true;
6207 
6208  return false;
6209  }
6210 
6211  // C++11 [dcl.meaning]p1:
6212  // [...] "The nested-name-specifier of the qualified declarator-id shall
6213  // not begin with a decltype-specifer"
6214  NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6215  while (SpecLoc.getPrefix())
6216  SpecLoc = SpecLoc.getPrefix();
6217  if (isa_and_nonnull<DecltypeType>(
6218  SpecLoc.getNestedNameSpecifier()->getAsType()))
6219  Diag(Loc, diag::err_decltype_in_declarator)
6220  << SpecLoc.getTypeLoc().getSourceRange();
6221 
6222  return false;
6223 }
6224 
6226  MultiTemplateParamsArg TemplateParamLists) {
6227  // TODO: consider using NameInfo for diagnostic.
6228  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6229  DeclarationName Name = NameInfo.getName();
6230 
6231  // All of these full declarators require an identifier. If it doesn't have
6232  // one, the ParsedFreeStandingDeclSpec action should be used.
6233  if (D.isDecompositionDeclarator()) {
6234  return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6235  } else if (!Name) {
6236  if (!D.isInvalidType()) // Reject this if we think it is valid.
6237  Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6238  << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6239  return nullptr;
6240  } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6241  return nullptr;
6242 
6243  // The scope passed in may not be a decl scope. Zip up the scope tree until
6244  // we find one that is.
6245  while ((S->getFlags() & Scope::DeclScope) == 0 ||
6246  (S->getFlags() & Scope::TemplateParamScope) != 0)
6247  S = S->getParent();
6248 
6249  DeclContext *DC = CurContext;
6250  if (D.getCXXScopeSpec().isInvalid())
6251  D.setInvalidType();
6252  else if (D.getCXXScopeSpec().isSet()) {
6253  if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6254  UPPC_DeclarationQualifier))
6255  return nullptr;
6256 
6257  bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6258  DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6259  if (!DC || isa<EnumDecl>(DC)) {
6260  // If we could not compute the declaration context, it's because the
6261  // declaration context is dependent but does not refer to a class,
6262  // class template, or class template partial specialization. Complain
6263  // and return early, to avoid the coming semantic disaster.
6264  Diag(D.getIdentifierLoc(),
6265  diag::err_template_qualified_declarator_no_match)
6266  << D.getCXXScopeSpec().getScopeRep()
6267  << D.getCXXScopeSpec().getRange();
6268  return nullptr;
6269  }
6270  bool IsDependentContext = DC->isDependentContext();
6271 
6272  if (!IsDependentContext &&
6273  RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6274  return nullptr;
6275 
6276  // If a class is incomplete, do not parse entities inside it.
6277  if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6278  Diag(D.getIdentifierLoc(),
6279  diag::err_member_def_undefined_record)
6280  << Name << DC << D.getCXXScopeSpec().getRange();
6281  return nullptr;
6282  }
6283  if (!D.getDeclSpec().isFriendSpecified()) {
6284  if (diagnoseQualifiedDeclaration(
6285  D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6287  if (DC->isRecord())
6288  return nullptr;
6289 
6290  D.setInvalidType();
6291  }
6292  }
6293 
6294  // Check whether we need to rebuild the type of the given
6295  // declaration in the current instantiation.
6296  if (EnteringContext && IsDependentContext &&
6297  TemplateParamLists.size() != 0) {
6298  ContextRAII SavedContext(*this, DC);
6299  if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6300  D.setInvalidType();
6301  }
6302  }
6303 
6304  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6305  QualType R = TInfo->getType();
6306 
6307  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6308  UPPC_DeclarationType))
6309  D.setInvalidType();
6310 
6311  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6312  forRedeclarationInCurContext());
6313 
6314  // See if this is a redefinition of a variable in the same scope.
6315  if (!D.getCXXScopeSpec().isSet()) {
6316  bool IsLinkageLookup = false;
6317  bool CreateBuiltins = false;
6318 
6319  // If the declaration we're planning to build will be a function
6320  // or object with linkage, then look for another declaration with
6321  // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6322  //
6323  // If the declaration we're planning to build will be declared with
6324  // external linkage in the translation unit, create any builtin with
6325  // the same name.
6327  /* Do nothing*/;
6328  else if (CurContext->isFunctionOrMethod() &&
6330  R->isFunctionType())) {
6331  IsLinkageLookup = true;
6332  CreateBuiltins =
6333  CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6334  } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6336  CreateBuiltins = true;
6337 
6338  if (IsLinkageLookup) {
6339  Previous.clear(LookupRedeclarationWithLinkage);
6340  Previous.setRedeclarationKind(ForExternalRedeclaration);
6341  }
6342 
6343  LookupName(Previous, S, CreateBuiltins);
6344  } else { // Something like "int foo::x;"
6345  LookupQualifiedName(Previous, DC);
6346 
6347  // C++ [dcl.meaning]p1:
6348  // When the declarator-id is qualified, the declaration shall refer to a
6349  // previously declared member of the class or namespace to which the
6350  // qualifier refers (or, in the case of a namespace, of an element of the
6351  // inline namespace set of that namespace (7.3.1)) or to a specialization
6352  // thereof; [...]
6353  //
6354  // Note that we already checked the context above, and that we do not have
6355  // enough information to make sure that Previous contains the declaration
6356  // we want to match. For example, given:
6357  //
6358  // class X {
6359  // void f();
6360  // void f(float);
6361  // };
6362  //
6363  // void X::f(int) { } // ill-formed
6364  //
6365  // In this case, Previous will point to the overload set
6366  // containing the two f's declared in X, but neither of them
6367  // matches.
6368 
6369  // C++ [dcl.meaning]p1:
6370  // [...] the member shall not merely have been introduced by a
6371  // using-declaration in the scope of the class or namespace nominated by
6372  // the nested-name-specifier of the declarator-id.
6374  }
6375 
6376  if (Previous.isSingleResult() &&
6377  Previous.getFoundDecl()->isTemplateParameter()) {
6378  // Maybe we will complain about the shadowed template parameter.
6379  if (!D.isInvalidType())
6380  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6381  Previous.getFoundDecl());
6382 
6383  // Just pretend that we didn't see the previous declaration.
6384  Previous.clear();
6385  }
6386 
6387  if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6388  // Forget that the previous declaration is the injected-class-name.
6389  Previous.clear();
6390 
6391  // In C++, the previous declaration we find might be a tag type
6392  // (class or enum). In this case, the new declaration will hide the
6393  // tag type. Note that this applies to functions, function templates, and
6394  // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6395  if (Previous.isSingleTagDecl() &&
6397  (TemplateParamLists.size() == 0 || R->isFunctionType()))
6398  Previous.clear();
6399 
6400  // Check that there are no default arguments other than in the parameters
6401  // of a function declaration (C++ only).
6402  if (getLangOpts().CPlusPlus)
6403  CheckExtraCXXDefaultArguments(D);
6404 
6405  NamedDecl *New;
6406 
6407  bool AddToScope = true;
6409  if (TemplateParamLists.size()) {
6410  Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6411  return nullptr;
6412  }
6413 
6414  New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6415  } else if (R->isFunctionType()) {
6416  New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6417  TemplateParamLists,
6418  AddToScope);
6419  } else {
6420  New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6421  AddToScope);
6422  }
6423 
6424  if (!New)
6425  return nullptr;
6426 
6427  // If this has an identifier and is not a function template specialization,
6428  // add it to the scope stack.
6429  if (New->getDeclName() && AddToScope)
6430  PushOnScopeChains(New, S);
6431 
6432  if (isInOpenMPDeclareTargetContext())
6433  checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6434 
6435  return New;
6436 }
6437 
6438 /// Helper method to turn variable array types into constant array
6439 /// types in certain situations which would otherwise be errors (for
6440 /// GCC compatibility).
6442  ASTContext &Context,
6443  bool &SizeIsNegative,
6444  llvm::APSInt &Oversized) {
6445  // This method tries to turn a variable array into a constant
6446  // array even when the size isn't an ICE. This is necessary
6447  // for compatibility with code that depends on gcc's buggy
6448  // constant expression folding, like struct {char x[(int)(char*)2];}
6449  SizeIsNegative = false;
6450  Oversized = 0;
6451 
6452  if (T->isDependentType())
6453  return QualType();
6454 
6455  QualifierCollector Qs;
6456  const Type *Ty = Qs.strip(T);
6457 
6458  if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6459  QualType Pointee = PTy->getPointeeType();
6460  QualType FixedType =
6461  TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6462  Oversized);
6463  if (FixedType.isNull()) return FixedType;
6464  FixedType = Context.getPointerType(FixedType);
6465  return Qs.apply(Context, FixedType);
6466  }
6467  if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6468  QualType Inner = PTy->getInnerType();
6469  QualType FixedType =
6470  TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6471  Oversized);
6472  if (FixedType.isNull()) return FixedType;
6473  FixedType = Context.getParenType(FixedType);
6474  return Qs.apply(Context, FixedType);
6475  }
6476 
6477  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6478  if (!VLATy)
6479  return QualType();
6480 
6481  QualType ElemTy = VLATy->getElementType();
6482  if (ElemTy->isVariablyModifiedType()) {
6483  ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6484  SizeIsNegative, Oversized);
6485  if (ElemTy.isNull())
6486  return QualType();
6487  }
6488 
6489  Expr::EvalResult Result;
6490  if (!VLATy->getSizeExpr() ||
6491  !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6492  return QualType();
6493 
6494  llvm::APSInt Res = Result.Val.getInt();
6495 
6496  // Check whether the array size is negative.
6497  if (Res.isSigned() && Res.isNegative()) {
6498  SizeIsNegative = true;
6499  return QualType();
6500  }
6501 
6502  // Check whether the array is too large to be addressed.
6503  unsigned ActiveSizeBits =
6504  (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6505  !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6506  ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6507  : Res.getActiveBits();
6508  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6509  Oversized = Res;
6510  return QualType();
6511  }
6512 
6513  QualType FoldedArrayType = Context.getConstantArrayType(
6514  ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6515  return Qs.apply(Context, FoldedArrayType);
6516 }
6517 
6518 static void
6520  SrcTL = SrcTL.getUnqualifiedLoc();
6521  DstTL = DstTL.getUnqualifiedLoc();
6522  if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6523  PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6524  FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6525  DstPTL.getPointeeLoc());
6526  DstPTL.setStarLoc(SrcPTL.getStarLoc());
6527  return;
6528  }
6529  if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6530  ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6531  FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6532  DstPTL.getInnerLoc());
6533  DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6534  DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6535  return;
6536  }
6537  ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6538  ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6539  TypeLoc SrcElemTL = SrcATL.getElementLoc();
6540  TypeLoc DstElemTL = DstATL.getElementLoc();
6541  if (VariableArrayTypeLoc SrcElemATL =
6542  SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6543  ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6544  FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6545  } else {
6546  DstElemTL.initializeFullCopy(SrcElemTL);
6547  }
6548  DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6549  DstATL.setSizeExpr(SrcATL.getSizeExpr());
6550  DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6551 }
6552 
6553 /// Helper method to turn variable array types into constant array
6554 /// types in certain situations which would otherwise be errors (for
6555 /// GCC compatibility).
6556 static TypeSourceInfo*
6558  ASTContext &Context,
6559  bool &SizeIsNegative,
6560  llvm::APSInt &Oversized) {
6561  QualType FixedTy
6562  = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6563  SizeIsNegative, Oversized);
6564  if (FixedTy.isNull())
6565  return nullptr;
6566  TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6568  FixedTInfo->getTypeLoc());
6569  return FixedTInfo;
6570 }
6571 
6572 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6573 /// true if we were successful.
6575  QualType &T, SourceLocation Loc,
6576  unsigned FailedFoldDiagID) {
6577  bool SizeIsNegative;
6578  llvm::APSInt Oversized;
6580  TInfo, Context, SizeIsNegative, Oversized);
6581  if (FixedTInfo) {
6582  Diag(Loc, diag::ext_vla_folded_to_constant);
6583  TInfo = FixedTInfo;
6584  T = FixedTInfo->getType();
6585  return true;
6586  }
6587 
6588  if (SizeIsNegative)
6589  Diag(Loc, diag::err_typecheck_negative_array_size);
6590  else if (Oversized.getBoolValue())
6591  Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6592  else if (FailedFoldDiagID)
6593  Diag(Loc, FailedFoldDiagID);
6594  return false;
6595 }
6596 
6597 /// Register the given locally-scoped extern "C" declaration so
6598 /// that it can be found later for redeclarations. We include any extern "C"
6599 /// declaration that is not visible in the translation unit here, not just
6600 /// function-scope declarations.
6601 void
6603  if (!getLangOpts().CPlusPlus &&
6605  // Don't need to track declarations in the TU in C.
6606  return;
6607 
6608  // Note that we have a locally-scoped external with this name.
6610 }
6611 
6613  // FIXME: We can have multiple results via __attribute__((overloadable)).
6614  auto Result = Context.getExternCContextDecl()->lookup(Name);
6615  return Result.empty() ? nullptr : *Result.begin();
6616 }
6617 
6618 /// Diagnose function specifiers on a declaration of an identifier that
6619 /// does not identify a function.
6621  // FIXME: We should probably indicate the identifier in question to avoid
6622  // confusion for constructs like "virtual int a(), b;"
6623  if (DS.isVirtualSpecified())
6624  Diag(DS.getVirtualSpecLoc(),
6625  diag::err_virtual_non_function);
6626 
6627  if (DS.hasExplicitSpecifier())
6628  Diag(DS.getExplicitSpecLoc(),
6629  diag::err_explicit_non_function);
6630 
6631  if (DS.isNoreturnSpecified())
6632  Diag(DS.getNoreturnSpecLoc(),
6633  diag::err_noreturn_non_function);
6634 }
6635 
6636 NamedDecl*
6639  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6640  if (D.getCXXScopeSpec().isSet()) {
6641  Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6642  << D.getCXXScopeSpec().getRange();
6643  D.setInvalidType();
6644  // Pretend we didn't see the scope specifier.
6645  DC = CurContext;
6646  Previous.clear();
6647  }
6648 
6649  DiagnoseFunctionSpecifiers(D.getDeclSpec());
6650 
6651  if (D.getDeclSpec().isInlineSpecified())
6652  Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6653  << getLangOpts().CPlusPlus17;
6655  Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6656  << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6657 
6661  diag::err_deduction_guide_invalid_specifier)
6662  << "typedef";
6663  else
6664  Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6665  << D.getName().getSourceRange();
6666  return nullptr;
6667  }
6668 
6669  TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6670  if (!NewTD) return nullptr;
6671 
6672  // Handle attributes prior to checking for duplicates in MergeVarDecl
6673  ProcessDeclAttributes(S, NewTD, D);
6674 
6675  CheckTypedefForVariablyModifiedType(S, NewTD);
6676 
6677  bool Redeclaration = D.isRedeclaration();
6678  NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6679  D.setRedeclaration(Redeclaration);
6680  return ND;
6681 }
6682 
6683 void
6685  // C99 6.7.7p2: If a typedef name specifies a variably modified type
6686  // then it shall have block scope.
6687  // Note that variably modified types must be fixed before merging the decl so
6688  // that redeclarations will match.
6689  TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6690  QualType T = TInfo->getType();
6691  if (T->isVariablyModifiedType()) {
6692  setFunctionHasBranchProtectedScope();
6693 
6694  if (S->getFnParent() == nullptr) {
6695  bool SizeIsNegative;
6696  llvm::APSInt Oversized;
6697  TypeSourceInfo *FixedTInfo =
6699  SizeIsNegative,
6700  Oversized);
6701  if (FixedTInfo) {
6702  Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6703  NewTD->setTypeSourceInfo(FixedTInfo);
6704  } else {
6705  if (SizeIsNegative)
6706  Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6707  else if (T->isVariableArrayType())
6708  Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6709  else if (Oversized.getBoolValue())
6710  Diag(NewTD->getLocation(), diag::err_array_too_large)
6711  << toString(Oversized, 10);
6712  else
6713  Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6714  NewTD->setInvalidDecl();
6715  }
6716  }
6717  }
6718 }
6719 
6720 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6721 /// declares a typedef-name, either using the 'typedef' type specifier or via
6722 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6723 NamedDecl*
6725  LookupResult &Previous, bool &Redeclaration) {
6726 
6727  // Find the shadowed declaration before filtering for scope.
6728  NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6729 
6730  // Merge the decl with the existing one if appropriate. If the decl is
6731  // in an outer scope, it isn't the same thing.
6732  FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6733  /*AllowInlineNamespace*/false);
6735  if (!Previous.empty()) {
6736  Redeclaration = true;
6737  MergeTypedefNameDecl(S, NewTD, Previous);
6738  } else {
6739  inferGslPointerAttribute(NewTD);
6740  }
6741 
6742  if (ShadowedDecl && !Redeclaration)
6743  CheckShadow(NewTD, ShadowedDecl, Previous);
6744 
6745  // If this is the C FILE type, notify the AST context.
6746  if (IdentifierInfo *II = NewTD->getIdentifier())
6747  if (!NewTD->isInvalidDecl() &&
6749  if (II->isStr("FILE"))
6750  Context.setFILEDecl(NewTD);
6751  else if (II->isStr("jmp_buf"))
6752  Context.setjmp_bufDecl(NewTD);
6753  else if (II->isStr("sigjmp_buf"))
6754  Context.setsigjmp_bufDecl(NewTD);
6755  else if (II->isStr("ucontext_t"))
6756  Context.setucontext_tDecl(NewTD);
6757  }
6758 
6759  return NewTD;
6760 }
6761 
6762 /// Determines whether the given declaration is an out-of-scope
6763 /// previous declaration.
6764 ///
6765 /// This routine should be invoked when name lookup has found a
6766 /// previous declaration (PrevDecl) that is not in the scope where a
6767 /// new declaration by the same name is being introduced. If the new
6768 /// declaration occurs in a local scope, previous declarations with
6769 /// linkage may still be considered previous declarations (C99
6770 /// 6.2.2p4-5, C++ [basic.link]p6).
6771 ///
6772 /// \param PrevDecl the previous declaration found by name
6773 /// lookup
6774 ///
6775 /// \param DC the context in which the new declaration is being
6776 /// declared.
6777 ///
6778 /// \returns true if PrevDecl is an out-of-scope previous declaration
6779 /// for a new delcaration with the same name.
6780 static bool
6782  ASTContext &Context) {
6783  if (!PrevDecl)
6784  return false;
6785 
6786  if (!PrevDecl->hasLinkage())
6787  return false;
6788 
6789  if (Context.getLangOpts().CPlusPlus) {
6790  // C++ [basic.link]p6:
6791  // If there is a visible declaration of an entity with linkage
6792  // having the same name and type, ignoring entities declared
6793  // outside the innermost enclosing namespace scope, the block
6794  // scope declaration declares that same entity and receives the
6795  // linkage of the previous declaration.
6796  DeclContext *OuterContext = DC->getRedeclContext();
6797  if (!OuterContext->isFunctionOrMethod())
6798  // This rule only applies to block-scope declarations.
6799  return false;
6800 
6801  DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6802  if (PrevOuterContext->isRecord())
6803  // We found a member function: ignore it.
6804  return false;
6805 
6806  // Find the innermost enclosing namespace for the new and
6807  // previous declarations.
6808  OuterContext = OuterContext->getEnclosingNamespaceContext();
6809  PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6810 
6811  // The previous declaration is in a different namespace, so it
6812  // isn't the same function.
6813  if (!OuterContext->Equals(PrevOuterContext))
6814  return false;
6815  }
6816 
6817  return true;
6818 }
6819 
6821  CXXScopeSpec &SS = D.getCXXScopeSpec();
6822  if (!SS.isSet()) return;
6824 }
6825 
6827  QualType type = decl->getType();
6828  Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6829  if (lifetime == Qualifiers::OCL_Autoreleasing) {
6830  // Various kinds of declaration aren't allowed to be __autoreleasing.
6831  unsigned kind = -1U;
6832  if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6833  if (var->hasAttr<BlocksAttr>())
6834  kind = 0; // __block
6835  else if (!var->hasLocalStorage())
6836  kind = 1; // global
6837  } else if (isa<ObjCIvarDecl>(decl)) {
6838  kind = 3; // ivar
6839  } else if (isa<FieldDecl>(decl)) {
6840  kind = 2; // field
6841  }
6842 
6843  if (kind != -1U) {
6844  Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6845  << kind;
6846  }
6847  } else if (lifetime == Qualifiers::OCL_None) {
6848  // Try to infer lifetime.
6849  if (!type->isObjCLifetimeType())
6850  return false;
6851 
6852  lifetime = type->getObjCARCImplicitLifetime();
6853  type = Context.getLifetimeQualifiedType(type, lifetime);
6854  decl->setType(type);
6855  }
6856 
6857  if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6858  // Thread-local variables cannot have lifetime.
6859  if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6860  var->getTLSKind()) {
6861  Diag(var->getLocation(), diag::err_arc_thread_ownership)
6862  << var->getType();
6863  return true;
6864  }
6865  }
6866 
6867  return false;
6868 }
6869 
6871  if (Decl->getType().hasAddressSpace())
6872  return;
6873  if (Decl->getType()->isDependentType())
6874  return;
6875  if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6876  QualType Type = Var->getType();
6877  if (Type->isSamplerT() || Type->isVoidType())
6878  return;
6879  LangAS ImplAS = LangAS::opencl_private;
6880  // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6881  // __opencl_c_program_scope_global_variables feature, the address space
6882  // for a variable at program scope or a static or extern variable inside
6883  // a function are inferred to be __global.
6884  if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6885  Var->hasGlobalStorage())
6886  ImplAS = LangAS::opencl_global;
6887  // If the original type from a decayed type is an array type and that array
6888  // type has no address space yet, deduce it now.
6889  if (auto DT = dyn_cast<DecayedType>(Type)) {
6890  auto OrigTy = DT->getOriginalType();
6891  if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6892  // Add the address space to the original array type and then propagate
6893  // that to the element type through `getAsArrayType`.
6894  OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6895  OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6896  // Re-generate the decayed type.
6897  Type = Context.getDecayedType(OrigTy);
6898  }
6899  }
6900  Type = Context.getAddrSpaceQualType(Type, ImplAS);
6901  // Apply any qualifiers (including address space) from the array type to
6902  // the element type. This implements C99 6.7.3p8: "If the specification of
6903  // an array type includes any type qualifiers, the element type is so
6904  // qualified, not the array type."
6905  if (Type->isArrayType())
6906  Type = QualType(Context.getAsArrayType(Type), 0);
6907  Decl->setType(Type);
6908  }
6909 }
6910 
6912  // Ensure that an auto decl is deduced otherwise the checks below might cache
6913  // the wrong linkage.
6914  assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6915 
6916  // 'weak' only applies to declarations with external linkage.
6917  if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6918  if (!ND.isExternallyVisible()) {
6919  S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6920  ND.dropAttr<WeakAttr>();
6921  }
6922  }
6923  if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6924  if (ND.isExternallyVisible()) {
6925  S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6926  ND.dropAttr<WeakRefAttr>();
6927  ND.dropAttr<AliasAttr>();
6928  }
6929  }
6930 
6931  if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6932  if (VD->hasInit()) {
6933  if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6934  assert(VD->isThisDeclarationADefinition() &&
6935  !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6936  S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6937  VD->dropAttr<AliasAttr>();
6938  }
6939  }
6940  }
6941 
6942  // 'selectany' only applies to externally visible variable declarations.
6943  // It does not apply to functions.
6944  if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6945  if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6946  S.Diag(Attr->getLocation(),
6947  diag::err_attribute_selectany_non_extern_data);
6948  ND.dropAttr<SelectAnyAttr>();
6949  }
6950  }
6951 
6952  if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6953  auto *VD = dyn_cast<VarDecl>(&ND);
6954  bool IsAnonymousNS = false;
6955  bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6956  if (VD) {
6957  const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6958  while (NS && !IsAnonymousNS) {
6959  IsAnonymousNS = NS->isAnonymousNamespace();
6960  NS = dyn_cast<NamespaceDecl>(NS->getParent());
6961  }
6962  }
6963  // dll attributes require external linkage. Static locals may have external
6964  // linkage but still cannot be explicitly imported or exported.
6965  // In Microsoft mode, a variable defined in anonymous namespace must have
6966  // external linkage in order to be exported.
6967  bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6968  if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6969  (!AnonNSInMicrosoftMode &&
6970  (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6971  S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6972  << &ND << Attr;
6973  ND.setInvalidDecl();
6974  }
6975  }
6976 
6977  // Check the attributes on the function type, if any.
6978  if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6979  // Don't declare this variable in the second operand of the for-statement;
6980  // GCC miscompiles that by ending its lifetime before evaluating the
6981  // third operand. See gcc.gnu.org/PR86769.
6982  AttributedTypeLoc ATL;
6983  for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6984  (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6985  TL = ATL.getModifiedLoc()) {
6986  // The [[lifetimebound]] attribute can be applied to the implicit object
6987  // parameter of a non-static member function (other than a ctor or dtor)
6988  // by applying it to the function type.
6989  if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6990  const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6991  if (!MD || MD->isStatic()) {
6992  S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6993  << !MD << A->getRange();
6994  } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6995  S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6996  << isa<CXXDestructorDecl>(MD) << A->getRange();
6997  }
6998  }
6999  }
7000  }
7001 }
7002 
7004  NamedDecl *NewDecl,
7005  bool IsSpecialization,
7006  bool IsDefinition) {
7007  if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7008  return;
7009 
7010  bool IsTemplate = false;
7011  if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7012  OldDecl = OldTD->getTemplatedDecl();
7013  IsTemplate = true;
7014  if (!IsSpecialization)
7015  IsDefinition = false;
7016  }
7017  if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7018  NewDecl = NewTD->getTemplatedDecl();
7019  IsTemplate = true;
7020  }
7021 
7022  if (!OldDecl || !NewDecl)
7023  return;
7024 
7025  const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7026  const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7027  const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7028  const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7029 
7030  // dllimport and dllexport are inheritable attributes so we have to exclude
7031  // inherited attribute instances.
7032  bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7033  (NewExportAttr && !NewExportAttr->isInherited());
7034 
7035  // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7036  // the only exception being explicit specializations.
7037  // Implicitly generated declarations are also excluded for now because there
7038  // is no other way to switch these to use dllimport or dllexport.
7039  bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7040 
7041  if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7042  // Allow with a warning for free functions and global variables.
7043  bool JustWarn = false;
7044  if (!OldDecl->isCXXClassMember()) {
7045  auto *VD = dyn_cast<VarDecl>(OldDecl);
7046  if (VD && !VD->getDescribedVarTemplate())
7047  JustWarn = true;
7048  auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7049  if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7050  JustWarn = true;
7051  }
7052 
7053  // We cannot change a declaration that's been used because IR has already
7054  // been emitted. Dllimported functions will still work though (modulo
7055  // address equality) as they can use the thunk.
7056  if (OldDecl->isUsed())
7057  if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7058  JustWarn = false;
7059 
7060  unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7061  : diag::err_attribute_dll_redeclaration;
7062  S.Diag(NewDecl->getLocation(), DiagID)
7063  << NewDecl
7064  << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7065  S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7066  if (!JustWarn) {
7067  NewDecl->setInvalidDecl();
7068  return;
7069  }
7070  }
7071 
7072  // A redeclaration is not allowed to drop a dllimport attribute, the only
7073  // exceptions being inline function definitions (except for function
7074  // templates), local extern declarations, qualified friend declarations or
7075  // special MSVC extension: in the last case, the declaration is treated as if
7076  // it were marked dllexport.
7077  bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7078  bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7079  if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7080  // Ignore static data because out-of-line definitions are diagnosed
7081  // separately.
7082  IsStaticDataMember = VD->isStaticDataMember();
7083  IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7085  } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7086  IsInline = FD->isInlined();
7087  IsQualifiedFriend = FD->getQualifier() &&
7088  FD->getFriendObjectKind() == Decl::FOK_Declared;
7089  }
7090 
7091  if (OldImportAttr && !HasNewAttr &&
7092  (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7093  !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7094  if (IsMicrosoftABI && IsDefinition) {
7095  if (IsSpecialization) {
7096  S.Diag(
7097  NewDecl->getLocation(),
7098  diag::err_attribute_dllimport_function_specialization_definition);
7099  S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7100  NewDecl->dropAttr<DLLImportAttr>();
7101  } else {
7102  S.Diag(NewDecl->getLocation(),
7103  diag::warn_redeclaration_without_import_attribute)
7104  << NewDecl;
7105  S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7106  NewDecl->dropAttr<DLLImportAttr>();
7107  NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7108  S.Context, NewImportAttr->getRange()));
7109  }
7110  } else if (IsMicrosoftABI && IsSpecialization) {
7111  assert(!IsDefinition);
7112  // MSVC allows this. Keep the inherited attribute.
7113  } else {
7114  S.Diag(NewDecl->getLocation(),
7115  diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7116  << NewDecl << OldImportAttr;
7117  S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7118  S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7119  OldDecl->dropAttr<DLLImportAttr>();
7120  NewDecl->dropAttr<DLLImportAttr>();
7121  }
7122  } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7123  // In MinGW, seeing a function declared inline drops the dllimport
7124  // attribute.
7125  OldDecl->dropAttr<DLLImportAttr>();
7126  NewDecl->dropAttr<DLLImportAttr>();
7127  S.Diag(NewDecl->getLocation(),
7128  diag::warn_dllimport_dropped_from_inline_function)
7129  << NewDecl << OldImportAttr;
7130  }
7131 
7132  // A specialization of a class template member function is processed here
7133  // since it's a redeclaration. If the parent class is dllexport, the
7134  // specialization inherits that attribute. This doesn't happen automatically
7135  // since the parent class isn't instantiated until later.
7136  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7137  if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7138  !NewImportAttr && !NewExportAttr) {
7139  if (const DLLExportAttr *ParentExportAttr =
7140  MD->getParent()->getAttr<DLLExportAttr>()) {
7141  DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7142  NewAttr->setInherited(true);
7143  NewDecl->addAttr(NewAttr);
7144  }
7145  }
7146  }
7147 }
7148 
7149 /// Given that we are within the definition of the given function,
7150 /// will that definition behave like C99's 'inline', where the
7151 /// definition is discarded except for optimization purposes?
7153  // Try to avoid calling GetGVALinkageForFunction.
7154 
7155  // All cases of this require the 'inline' keyword.
7156  if (!FD->isInlined()) return false;
7157 
7158  // This is only possible in C++ with the gnu_inline attribute.
7159  if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7160  return false;
7161 
7162  // Okay, go ahead and call the relatively-more-expensive function.
7164 }
7165 
7166 /// Determine whether a variable is extern "C" prior to attaching
7167 /// an initializer. We can't just call isExternC() here, because that
7168 /// will also compute and cache whether the declaration is externally
7169 /// visible, which might change when we attach the initializer.
7170 ///
7171 /// This can only be used if the declaration is known to not be a
7172 /// redeclaration of an internal linkage declaration.
7173 ///
7174 /// For instance:
7175 ///
7176 /// auto x = []{};
7177 ///
7178 /// Attaching the initializer here makes this declaration not externally
7179 /// visible, because its type has internal linkage.
7180 ///
7181 /// FIXME: This is a hack.
7182 template<typename T>
7183 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7184  if (S.getLangOpts().CPlusPlus) {
7185  // In C++, the overloadable attribute negates the effects of extern "C".
7186  if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7187  return false;
7188 
7189  // So do CUDA's host/device attributes.
7190  if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7191  D->template hasAttr<CUDAHostAttr>()))
7192  return false;
7193  }
7194  return D->isExternC();
7195 }
7196 
7197 static bool shouldConsiderLinkage(const VarDecl *VD) {
7198  const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7199  if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7200  isa<OMPDeclareMapperDecl>(DC))
7201  return VD->hasExternalStorage();
7202  if (DC->isFileContext())
7203  return true;
7204  if (DC->isRecord())
7205  return false;
7206  if (DC->getDeclKind() == Decl::HLSLBuffer)
7207  return false;
7208 
7209  if (isa<RequiresExprBodyDecl>(DC))
7210  return false;
7211  llvm_unreachable("Unexpected context");
7212 }
7213 
7214 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7215  const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7216  if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7217  isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7218  return true;
7219  if (DC->isRecord())
7220  return false;
7221  llvm_unreachable("Unexpected context");
7222 }
7223 
7224 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7226  // Check decl attributes on the DeclSpec.
7228  return true;
7229 
7230  // Walk the declarator structure, checking decl attributes that were in a type
7231  // position to the decl itself.
7232  for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7233  if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7234  return true;
7235  }
7236 
7237  // Finally, check attributes on the decl itself.
7238  return PD.getAttributes().hasAttribute(Kind) ||
7240 }
7241 
7242 /// Adjust the \c DeclContext for a function or variable that might be a
7243 /// function-local external declaration.
7245  if (!DC->isFunctionOrMethod())
7246  return false;
7247 
7248  // If this is a local extern function or variable declared within a function
7249  // template, don't add it into the enclosing namespace scope until it is
7250  // instantiated; it might have a dependent type right now.
7251  if (DC->isDependentContext())
7252  return true;
7253 
7254  // C++11 [basic.link]p7:
7255  // When a block scope declaration of an entity with linkage is not found to
7256  // refer to some other declaration, then that entity is a member of the
7257  // innermost enclosing namespace.
7258  //
7259  // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7260  // semantically-enclosing namespace, not a lexically-enclosing one.
7261  while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7262  DC = DC->getParent();
7263  return true;
7264 }
7265 
7266 /// Returns true if given declaration has external C language linkage.
7267 static bool isDeclExternC(const Decl *D) {
7268  if (const auto *FD = dyn_cast<FunctionDecl>(D))
7269  return FD->isExternC();
7270  if (const auto *VD = dyn_cast<VarDecl>(D))
7271  return VD->isExternC();
7272 
7273  llvm_unreachable("Unknown type of decl!");
7274 }
7275 
7276 /// Returns true if there hasn't been any invalid type diagnosed.
7277 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7278  DeclContext *DC = NewVD->getDeclContext();
7279  QualType R = NewVD->getType();
7280 
7281  // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7282  // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7283  // argument.
7284  if (R->isImageType() || R->isPipeType()) {
7285  Se.Diag(NewVD->getLocation(),
7286  diag::err_opencl_type_can_only_be_used_as_function_parameter)
7287  << R;
7288  NewVD->setInvalidDecl();
7289  return false;
7290  }
7291 
7292  // OpenCL v1.2 s6.9.r:
7293  // The event type cannot be used to declare a program scope variable.
7294  // OpenCL v2.0 s6.9.q:
7295  // The clk_event_t and reserve_id_t types cannot be declared in program
7296  // scope.
7297  if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7298  if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7299  Se.Diag(NewVD->getLocation(),
7300  diag::err_invalid_type_for_program_scope_var)
7301  << R;
7302  NewVD->setInvalidDecl();
7303  return false;
7304  }
7305  }
7306 
7307  // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7308  if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7309  Se.getLangOpts())) {
7310  QualType NR = R.getCanonicalType();
7311  while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7312  NR->isReferenceType()) {
7314  NR->isFunctionReferenceType()) {
7315  Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7316  << NR->isReferenceType();
7317  NewVD->setInvalidDecl();
7318  return false;
7319  }
7320  NR = NR->getPointeeType();
7321  }
7322  }
7323 
7324  if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7325  Se.getLangOpts())) {
7326  // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7327  // half array type (unless the cl_khr_fp16 extension is enabled).
7328  if (Se.Context.getBaseElementType(R)->isHalfType()) {
7329  Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7330  NewVD->setInvalidDecl();
7331  return false;
7332  }
7333  }
7334 
7335  // OpenCL v1.2 s6.9.r:
7336  // The event type cannot be used with the __local, __constant and __global
7337  // address space qualifiers.
7338  if (R->isEventT()) {
7340  Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7341  NewVD->setInvalidDecl();
7342  return false;
7343  }
7344  }
7345 
7346  if (R->isSamplerT()) {
7347  // OpenCL v1.2 s6.9.b p4:
7348  // The sampler type cannot be used with the __local and __global address
7349  // space qualifiers.
7352  Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7353  NewVD->setInvalidDecl();
7354  }
7355 
7356  // OpenCL v1.2 s6.12.14.1:
7357  // A global sampler must be declared with either the constant address
7358  // space qualifier or with the const qualifier.
7359  if (DC->isTranslationUnit() &&
7361  R.isConstQualified())) {
7362  Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7363  NewVD->setInvalidDecl();
7364  }
7365  if (NewVD->isInvalidDecl())
7366  return false;
7367  }
7368 
7369  return true;
7370 }
7371 
7372 template <typename AttrTy>
7373 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7374  const TypedefNameDecl *TND = TT->getDecl();
7375  if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7376  AttrTy *Clone = Attribute->clone(S.Context);
7377  Clone->setInherited(true);
7378  D->addAttr(Clone);
7379  }
7380 }
7381 
7382 // This function emits warning and a corresponding note based on the
7383 // ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7384 // declarations of an annotated type must be const qualified.
7386  QualType VarType = VD->getType().getCanonicalType();
7387 
7388  // Ignore local declarations (for now) and those with const qualification.
7389  // TODO: Local variables should not be allowed if their type declaration has
7390  // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7391  if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7392  return;
7393 
7394  if (VarType->isArrayType()) {
7395  // Retrieve element type for array declarations.
7396  VarType = S.getASTContext().getBaseElementType(VarType);
7397  }
7398 
7399  const RecordDecl *RD = VarType->getAsRecordDecl();
7400 
7401  // Check if the record declaration is present and if it has any attributes.
7402  if (RD == nullptr)
7403  return;
7404 
7405  if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7406  S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7407  S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7408  return;
7409  }
7410 }
7411 
7413  Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7414  LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7415  bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7416  QualType R = TInfo->getType();
7417  DeclarationName Name = GetNameForDeclarator(D).getName();
7418 
7419  IdentifierInfo *II = Name.getAsIdentifierInfo();
7420 
7421  if (D.isDecompositionDeclarator()) {
7422  // Take the name of the first declarator as our name for diagnostic
7423  // purposes.
7424  auto &Decomp = D.getDecompositionDeclarator();
7425  if (!Decomp.bindings().empty()) {
7426  II = Decomp.bindings()[0].Name;
7427  Name = II;
7428  }
7429  } else if (!II) {
7430  Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7431  return nullptr;
7432  }
7433 
7434 
7437 
7438  // dllimport globals without explicit storage class are treated as extern. We
7439  // have to change the storage class this early to get the right DeclContext.
7440  if (SC == SC_None && !DC->isRecord() &&
7441  hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7442  !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7443  SC = SC_Extern;
7444 
7445  DeclContext *OriginalDC = DC;
7446  bool IsLocalExternDecl = SC == SC_Extern &&
7447  adjustContextForLocalExternDecl(DC);
7448 
7449  if (SCSpec == DeclSpec::SCS_mutable) {
7450  // mutable can only appear on non-static class members, so it's always
7451  // an error here
7452  Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7453  D.setInvalidType();
7454  SC = SC_None;
7455  }
7456 
7457  if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7458  !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7460  // In C++11, the 'register' storage class specifier is deprecated.
7461  // Suppress the warning in system macros, it's used in macros in some
7462  // popular C system headers, such as in glibc's htonl() macro.
7464  getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7465  : diag::warn_deprecated_register)
7467  }
7468 
7469  DiagnoseFunctionSpecifiers(D.getDeclSpec());
7470 
7471  if (!DC->isRecord() && S->getFnParent() == nullptr) {
7472  // C99 6.9p2: The storage-class specifiers auto and register shall not
7473  // appear in the declaration specifiers in an external declaration.
7474  // Global Register+Asm is a GNU extension we support.
7475  if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7476  Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7477  D.setInvalidType();
7478  }
7479  }
7480 
7481  // If this variable has a VLA type and an initializer, try to
7482  // fold to a constant-sized type. This is otherwise invalid.
7483  if (D.hasInitializer() && R->isVariableArrayType())
7484  tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7485  /*DiagID=*/0);
7486 
7487  bool IsMemberSpecialization = false;
7488  bool IsVariableTemplateSpecialization = false;
7489  bool IsPartialSpecialization = false;
7490  bool IsVariableTemplate = false;
7491  VarDecl *NewVD = nullptr;
7492  VarTemplateDecl *NewTemplate = nullptr;
7493  TemplateParameterList *TemplateParams = nullptr;
7494  if (!getLangOpts().CPlusPlus) {
7495  NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7496  II, R, TInfo, SC);
7497 
7498  if (R->getContainedDeducedType())
7499  ParsingInitForAutoVars.insert(NewVD);
7500 
7501  if (D.isInvalidType())
7502  NewVD->setInvalidDecl();
7503 
7505  NewVD->hasLocalStorage())
7506  checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7507  NTCUC_AutoVar, NTCUK_Destruct);
7508  } else {
7509  bool Invalid = false;
7510 
7511  if (DC->isRecord() && !CurContext->isRecord()) {
7512  // This is an out-of-line definition of a static data member.
7513  switch (SC) {
7514  case SC_None:
7515  break;
7516  case SC_Static:
7518  diag::err_static_out_of_line)
7520  break;
7521  case SC_Auto:
7522  case SC_Register:
7523  case SC_Extern:
7524  // [dcl.stc] p2: The auto or register specifiers shall be applied only
7525  // to names of variables declared in a block or to function parameters.
7526  // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7527  // of class members
7528 
7530  diag::err_storage_class_for_static_member)
7532  break;
7533  case SC_PrivateExtern:
7534  llvm_unreachable("C storage class in c++!");
7535  }
7536  }
7537 
7538  if (SC == SC_Static && CurContext->isRecord()) {
7539  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7540  // Walk up the enclosing DeclContexts to check for any that are
7541  // incompatible with static data members.
7542  const DeclContext *FunctionOrMethod = nullptr;
7543  const CXXRecordDecl *AnonStruct = nullptr;
7544  for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7545  if (Ctxt->isFunctionOrMethod()) {
7546  FunctionOrMethod = Ctxt;
7547  break;
7548  }
7549  const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7550  if (ParentDecl && !ParentDecl->getDeclName()) {
7551  AnonStruct = ParentDecl;
7552  break;
7553  }
7554  }
7555  if (FunctionOrMethod) {
7556  // C++ [class.static.data]p5: A local class shall not have static data
7557  // members.
7558  Diag(D.getIdentifierLoc(),
7559  diag::err_static_data_member_not_allowed_in_local_class)
7560  << Name << RD->getDeclName() << RD->getTagKind();
7561  } else if (AnonStruct) {
7562  // C++ [class.static.data]p4: Unnamed classes and classes contained
7563  // directly or indirectly within unnamed classes shall not contain
7564  // static data members.
7565  Diag(D.getIdentifierLoc(),
7566  diag::err_static_data_member_not_allowed_in_anon_struct)
7567  << Name << AnonStruct->getTagKind();
7568  Invalid = true;
7569  } else if (RD->isUnion()) {
7570  // C++98 [class.union]p1: If a union contains a static data member,
7571  // the program is ill-formed. C++11 drops this restriction.
7572  Diag(D.getIdentifierLoc(),
7573  getLangOpts().CPlusPlus11
7574  ? diag::warn_cxx98_compat_static_data_member_in_union
7575  : diag::ext_static_data_member_in_union) << Name;
7576  }
7577  }
7578  }
7579 
7580  // Match up the template parameter lists with the scope specifier, then
7581  // determine whether we have a template or a template specialization.
7582  bool InvalidScope = false;
7583  TemplateParams = MatchTemplateParametersToScopeSpecifier(
7585  D.getCXXScopeSpec(),
7587  ? D.getName().TemplateId
7588  : nullptr,
7589  TemplateParamLists,
7590  /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7591  Invalid |= InvalidScope;
7592 
7593  if (TemplateParams) {
7594  if (!TemplateParams->size() &&
7596  // There is an extraneous 'template<>' for this variable. Complain
7597  // about it, but allow the declaration of the variable.
7598  Diag(TemplateParams->getTemplateLoc(),
7599  diag::err_template_variable_noparams)
7600  << II
7601  << SourceRange(TemplateParams->getTemplateLoc(),
7602  TemplateParams->getRAngleLoc());
7603  TemplateParams = nullptr;
7604  } else {
7605  // Check that we can declare a template here.
7606  if (CheckTemplateDeclScope(S, TemplateParams))
7607  return nullptr;
7608 
7610  // This is an explicit specialization or a partial specialization.
7611  IsVariableTemplateSpecialization = true;
7612  IsPartialSpecialization = TemplateParams->size() > 0;
7613  } else { // if (TemplateParams->size() > 0)
7614  // This is a template declaration.
7615  IsVariableTemplate = true;
7616 
7617  // Only C++1y supports variable templates (N3651).
7618  Diag(D.getIdentifierLoc(),
7619  getLangOpts().CPlusPlus14
7620  ? diag::warn_cxx11_compat_variable_template
7621  : diag::ext_variable_template);
7622  }
7623  }
7624  } else {
7625  // Check that we can declare a member specialization here.
7626  if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7627  CheckTemplateDeclScope(S, TemplateParamLists.back()))
7628  return nullptr;
7629  assert((Invalid ||
7631  "should have a 'template<>' for this decl");
7632  }
7633 
7634  if (IsVariableTemplateSpecialization) {
7635  SourceLocation TemplateKWLoc =
7636  TemplateParamLists.size() > 0
7637  ? TemplateParamLists[0]->getTemplateLoc()
7638  : SourceLocation();
7639  DeclResult Res = ActOnVarTemplateSpecialization(
7640  S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7642  if (Res.isInvalid())
7643  return nullptr;
7644  NewVD = cast<VarDecl>(Res.get());
7645  AddToScope = false;
7646  } else if (D.isDecompositionDeclarator()) {
7647  NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7648  D.getIdentifierLoc(), R, TInfo, SC,
7649  Bindings);
7650  } else
7651  NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7652  D.getIdentifierLoc(), II, R, TInfo, SC);
7653 
7654  // If this is supposed to be a variable template, create it as such.
7655  if (IsVariableTemplate) {
7656  NewTemplate =
7657  VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7658  TemplateParams, NewVD);
7659  NewVD->setDescribedVarTemplate(NewTemplate);
7660  }
7661 
7662  // If this decl has an auto type in need of deduction, make a note of the
7663  // Decl so we can diagnose uses of it in its own initializer.
7664  if (R->getContainedDeducedType())
7665  ParsingInitForAutoVars.insert(NewVD);
7666 
7667  if (D.isInvalidType() || Invalid) {
7668  NewVD->setInvalidDecl();
7669  if (NewTemplate)
7670  NewTemplate->setInvalidDecl();
7671  }
7672 
7673  SetNestedNameSpecifier(*this, NewVD, D);
7674 
7675  // If we have any template parameter lists that don't directly belong to
7676  // the variable (matching the scope specifier), store them.
7677  unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7678  if (TemplateParamLists.size() > VDTemplateParamLists)
7680  Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7681  }
7682 
7683  if (D.getDeclSpec().isInlineSpecified()) {
7684  if (!getLangOpts().CPlusPlus) {
7685  Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7686  << 0;
7687  } else if (CurContext->isFunctionOrMethod()) {
7688  // 'inline' is not allowed on block scope variable declaration.
7690  diag::err_inline_declaration_block_scope) << Name
7692  } else {
7694  getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7695  : diag::ext_inline_variable);
7696  NewVD->setInlineSpecified();
7697  }
7698  }
7699 
7700  // Set the lexical context. If the declarator has a C++ scope specifier, the
7701  // lexical context will be different from the semantic context.
7702  NewVD->setLexicalDeclContext(CurContext);
7703  if (NewTemplate)
7704  NewTemplate->setLexicalDeclContext(CurContext);
7705 
7706  if (IsLocalExternDecl) {
7707  if (D.isDecompositionDeclarator())
7708  for (auto *B : Bindings)
7709  B->setLocalExternDecl();
7710  else
7711  NewVD->setLocalExternDecl();
7712  }
7713 
7714  bool EmitTLSUnsupportedError = false;
7716  // C++11 [dcl.stc]p4:
7717  // When thread_local is applied to a variable of block scope the
7718  // storage-class-specifier static is implied if it does not appear
7719  // explicitly.
7720  // Core issue: 'static' is not implied if the variable is declared
7721  // 'extern'.
7722  if (NewVD->hasLocalStorage() &&
7723  (SCSpec != DeclSpec::SCS_unspecified ||
7724  TSCS != DeclSpec::TSCS_thread_local ||
7725  !DC->isFunctionOrMethod()))
7727  diag::err_thread_non_global)
7728  << DeclSpec::getSpecifierName(TSCS);
7729  else if (!Context.getTargetInfo().isTLSSupported()) {
7730  if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7731  getLangOpts().SYCLIsDevice) {
7732  // Postpone error emission until we've collected attributes required to
7733  // figure out whether it's a host or device variable and whether the
7734  // error should be ignored.
7735  EmitTLSUnsupportedError = true;
7736  // We still need to mark the variable as TLS so it shows up in AST with
7737  // proper storage class for other tools to use even if we're not going
7738  // to emit any code for it.
7739  NewVD->setTSCSpec(TSCS);
7740  } else
7742  diag::err_thread_unsupported);
7743  } else
7744  NewVD->setTSCSpec(TSCS);
7745  }
7746 
7747  switch (D.getDeclSpec().getConstexprSpecifier()) {
7749  break;
7750 
7753  diag::err_constexpr_wrong_decl_kind)
7754  << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7755  [[fallthrough]];
7756 
7758  NewVD->setConstexpr(true);
7759  // C++1z [dcl.spec.constexpr]p1:
7760  // A static data member declared with the constexpr specifier is
7761  // implicitly an inline variable.
7762  if (NewVD->isStaticDataMember() &&
7763  (getLangOpts().CPlusPlus17 ||
7764  Context.getTargetInfo().getCXXABI().isMicrosoft()))
7765  NewVD->setImplicitlyInline();
7766  break;
7767 
7769  if (!NewVD->hasGlobalStorage())
7771  diag::err_constinit_local_variable);
7772  else
7773  NewVD->addAttr(ConstInitAttr::Create(
7774  Context, D.getDeclSpec().getConstexprSpecLoc(),
7775  AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7776  break;
7777  }
7778 
7779  // C99 6.7.4p3
7780  // An inline definition of a function with external linkage shall
7781  // not contain a definition of a modifiable object with static or
7782  // thread storage duration...
7783  // We only apply this when the function is required to be defined
7784  // elsewhere, i.e. when the function is not 'extern inline'. Note
7785  // that a local variable with thread storage duration still has to
7786  // be marked 'static'. Also note that it's possible to get these
7787  // semantics in C++ using __attribute__((gnu_inline)).
7788  if (SC == SC_Static && S->getFnParent() != nullptr &&
7789  !NewVD->getType().isConstQualified()) {
7790  FunctionDecl *CurFD = getCurFunctionDecl();
7791  if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7793  diag::warn_static_local_in_extern_inline);
7794  MaybeSuggestAddingStaticToDecl(CurFD);
7795  }
7796  }
7797 
7799  if (IsVariableTemplateSpecialization)
7800  Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7801  << (IsPartialSpecialization ? 1 : 0)
7804  else if (IsMemberSpecialization)
7805  Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7806  << 2
7808  else if (NewVD->hasLocalStorage())
7809  Diag(NewVD->getLocation(), diag::err_module_private_local)
7810  << 0 << NewVD
7814  else {
7815  NewVD->setModulePrivate();
7816  if (NewTemplate)
7817  NewTemplate->setModulePrivate();
7818  for (auto *B : Bindings)
7819  B->setModulePrivate();
7820  }
7821  }
7822 
7823  if (getLangOpts().OpenCL) {
7824  deduceOpenCLAddressSpace(NewVD);
7825 
7827  if (TSC != TSCS_unspecified) {
7829  diag::err_opencl_unknown_type_specifier)
7830  << getLangOpts().getOpenCLVersionString()
7831  << DeclSpec::getSpecifierName(TSC) << 1;
7832  NewVD->setInvalidDecl();
7833  }
7834  }
7835 
7836  // Handle attributes prior to checking for duplicates in MergeVarDecl
7837  ProcessDeclAttributes(S, NewVD, D);
7838 
7839  // FIXME: This is probably the wrong location to be doing this and we should
7840  // probably be doing this for more attributes (especially for function
7841  // pointer attributes such as format, warn_unused_result, etc.). Ideally
7842  // the code to copy attributes would be generated by TableGen.
7843  if (R->isFunctionPointerType())
7844  if (const auto *TT = R->getAs<TypedefType>())
7845  copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7846 
7847  if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7848  getLangOpts().SYCLIsDevice) {
7849  if (EmitTLSUnsupportedError &&
7850  ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7851  (getLangOpts().OpenMPIsDevice &&
7852  OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7854  diag::err_thread_unsupported);
7855 
7856  if (EmitTLSUnsupportedError &&
7857  (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7858  targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7859  // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7860  // storage [duration]."
7861  if (SC == SC_None && S->getFnParent() != nullptr &&
7862  (NewVD->hasAttr<CUDASharedAttr>() ||
7863  NewVD->hasAttr<CUDAConstantAttr>())) {
7864  NewVD->setStorageClass(SC_Static);
7865  }
7866  }
7867 
7868  // Ensure that dllimport globals without explicit storage class are treated as
7869  // extern. The storage class is set above using parsed attributes. Now we can
7870  // check the VarDecl itself.
7871  assert(!NewVD->hasAttr<DLLImportAttr>() ||
7872  NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7873  NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7874 
7875  // In auto-retain/release, infer strong retension for variables of
7876  // retainable type.
7877  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7878  NewVD->setInvalidDecl();
7879 
7880  // Handle GNU asm-label extension (encoded as an attribute).
7881  if (Expr *E = (Expr*)D.getAsmLabel()) {
7882  // The parser guarantees this is a string.
7883  StringLiteral *SE = cast<StringLiteral>(E);
7884  StringRef Label = SE->getString();
7885  if (S->getFnParent() != nullptr) {
7886  switch (SC) {
7887  case SC_None:
7888  case SC_Auto:
7889  Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7890  break;
7891  case SC_Register:
7892  // Local Named register
7893  if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7894  DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7895  Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7896  break;
7897  case SC_Static:
7898  case SC_Extern:
7899  case SC_PrivateExtern:
7900  break;
7901  }
7902  } else if (SC == SC_Register) {
7903  // Global Named register
7904  if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7905  const auto &TI = Context.getTargetInfo();
7906  bool HasSizeMismatch;
7907 
7908  if (!TI.isValidGCCRegisterName(Label))
7909  Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7910  else if (!TI.validateGlobalRegisterVariable(Label,
7911  Context.getTypeSize(R),
7912  HasSizeMismatch))
7913  Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7914  else if (HasSizeMismatch)
7915  Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7916  }
7917 
7918  if (!R->isIntegralType(Context) && !R->isPointerType()) {
7919  Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7920  NewVD->setInvalidDecl(true);
7921  }
7922  }
7923 
7924  NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7925  /*IsLiteralLabel=*/true,
7926  SE->getStrTokenLoc(0)));
7927  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7928  llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7929  ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7930  if (I != ExtnameUndeclaredIdentifiers.end()) {
7931  if (isDeclExternC(NewVD)) {
7932  NewVD->addAttr(I->second);
7933  ExtnameUndeclaredIdentifiers.erase(I);
7934  } else
7935  Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7936  << /*Variable*/1 << NewVD;
7937  }
7938  }
7939 
7940  // Find the shadowed declaration before filtering for scope.
7941  NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7942  ? getShadowedDeclaration(NewVD, Previous)
7943  : nullptr;
7944 
7945  // Don't consider existing declarations that are in a different
7946  // scope and are out-of-semantic-context declarations (if the new
7947  // declaration has linkage).
7948  FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7949  D.getCXXScopeSpec().isNotEmpty() ||
7950  IsMemberSpecialization ||
7951  IsVariableTemplateSpecialization);
7952 
7953  // Check whether the previous declaration is in the same block scope. This
7954  // affects whether we merge types with it, per C++11 [dcl.array]p3.
7955  if (getLangOpts().CPlusPlus &&
7956  NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7958  Previous.isSingleResult() && !Previous.isShadowed() &&
7959  isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7960 
7961  if (!getLangOpts().CPlusPlus) {
7962  D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7963  } else {
7964  // If this is an explicit specialization of a static data member, check it.
7965  if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7966  CheckMemberSpecialization(NewVD, Previous))
7967  NewVD->setInvalidDecl();
7968 
7969  // Merge the decl with the existing one if appropriate.
7970  if (!Previous.empty()) {
7971  if (Previous.isSingleResult() &&
7972  isa<FieldDecl>(Previous.getFoundDecl()) &&
7973  D.getCXXScopeSpec().isSet()) {
7974  // The user tried to define a non-static data member
7975  // out-of-line (C++ [dcl.meaning]p1).
7976  Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7977  << D.getCXXScopeSpec().getRange();
7978  Previous.clear();
7979  NewVD->setInvalidDecl();
7980  }
7981  } else if (D.getCXXScopeSpec().isSet()) {
7982  // No previous declaration in the qualifying scope.
7983  Diag(D.getIdentifierLoc(), diag::err_no_member)
7984  << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7985  << D.getCXXScopeSpec().getRange();
7986  NewVD->setInvalidDecl();
7987  }
7988 
7989  if (!IsVariableTemplateSpecialization)
7990  D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7991 
7992  if (NewTemplate) {
7993  VarTemplateDecl *PrevVarTemplate =
7994  NewVD->getPreviousDecl()
7996  : nullptr;
7997 
7998  // Check the template parameter list of this declaration, possibly
7999  // merging in the template parameter list from the previous variable
8000  // template declaration.
8001  if (CheckTemplateParameterList(
8002  TemplateParams,
8003  PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8004  : nullptr,
8005  (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8006  DC->isDependentContext())
8007  ? TPC_ClassTemplateMember
8008  : TPC_VarTemplate))
8009  NewVD->setInvalidDecl();
8010 
8011  // If we are providing an explicit specialization of a static variable
8012  // template, make a note of that.
8013  if (PrevVarTemplate &&
8014  PrevVarTemplate->getInstantiatedFromMemberTemplate())
8015  PrevVarTemplate->setMemberSpecialization();
8016  }
8017  }
8018 
8019  // Diagnose shadowed variables iff this isn't a redeclaration.
8020  if (ShadowedDecl && !D.isRedeclaration())
8021  CheckShadow(NewVD, ShadowedDecl, Previous);
8022 
8023  ProcessPragmaWeak(S, NewVD);
8024 
8025  // If this is the first declaration of an extern C variable, update
8026  // the map of such variables.
8027  if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8028  isIncompleteDeclExternC(*this, NewVD))
8029  RegisterLocallyScopedExternCDecl(NewVD, S);
8030 
8031  if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8032  MangleNumberingContext *MCtx;
8033  Decl *ManglingContextDecl;
8034  std::tie(MCtx, ManglingContextDecl) =
8035  getCurrentMangleNumberContext(NewVD->getDeclContext());
8036  if (MCtx) {
8037  Context.setManglingNumber(
8038  NewVD, MCtx->getManglingNumber(
8039  NewVD, getMSManglingNumber(getLangOpts(), S)));
8040  Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8041  }
8042  }
8043 
8044  // Special handling of variable named 'main'.
8045  if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
8047  !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
8048 
8049  // C++ [basic.start.main]p3
8050  // A program that declares a variable main at global scope is ill-formed.
8051  if (getLangOpts().CPlusPlus)
8052  Diag(D.getBeginLoc(), diag::err_main_global_variable);
8053 
8054  // In C, and external-linkage variable named main results in undefined
8055  // behavior.
8056  else if (NewVD->hasExternalFormalLinkage())
8057  Diag(D.getBeginLoc(), diag::warn_main_redefined);
8058  }
8059 
8060  if (D.isRedeclaration() && !Previous.empty()) {
8061  NamedDecl *Prev = Previous.getRepresentativeDecl();
8062  checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8063  D.isFunctionDefinition());
8064  }
8065 
8066  if (NewTemplate) {
8067  if (NewVD->isInvalidDecl())
8068  NewTemplate->setInvalidDecl();
8069  ActOnDocumentableDecl(NewTemplate);
8070  return NewTemplate;
8071  }
8072 
8073  if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8074  CompleteMemberSpecialization(NewVD, Previous);
8075 
8076  emitReadOnlyPlacementAttrWarning(*this, NewVD);
8077 
8078  return NewVD;
8079 }
8080 
8081 /// Enum describing the %select options in diag::warn_decl_shadow.
8090 };
8091 
8092 /// Determine what kind of declaration we're shadowing.
8094  const DeclContext *OldDC) {
8095  if (isa<TypeAliasDecl>(ShadowedDecl))
8096  return SDK_Using;
8097  else if (isa<TypedefDecl>(ShadowedDecl))
8098  return SDK_Typedef;
8099  else if (isa<BindingDecl>(ShadowedDecl))
8100  return SDK_StructuredBinding;
8101  else if (isa<RecordDecl>(OldDC))
8102  return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8103 
8104  return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8105 }
8106 
8107 /// Return the location of the capture if the given lambda captures the given
8108 /// variable \p VD, or an invalid source location otherwise.
8110  const VarDecl *VD) {
8111  for (const Capture &Capture : LSI->Captures) {
8112  if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8113  return Capture.getLocation();
8114  }
8115  return SourceLocation();
8116 }
8117 
8119  const LookupResult &R) {
8120  // Only diagnose if we're shadowing an unambiguous field or variable.
8122  return false;
8123 
8124  // Return false if warning is ignored.
8125  return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8126 }
8127 
8128 /// Return the declaration shadowed by the given variable \p D, or null
8129 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8131  const LookupResult &R) {
8132  if (!shouldWarnIfShadowedDecl(Diags, R))
8133  return nullptr;
8134 
8135  // Don't diagnose declarations at file scope.
8136  if (D->hasGlobalStorage())
8137  return nullptr;
8138 
8139  NamedDecl *ShadowedDecl = R.getFoundDecl();
8140  return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8141  : nullptr;
8142 }
8143 
8144 /// Return the declaration shadowed by the given typedef \p D, or null
8145 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8147  const LookupResult &R) {
8148  // Don't warn if typedef declaration is part of a class
8149  if (D->getDeclContext()->isRecord())
8150  return nullptr;
8151 
8152  if (!shouldWarnIfShadowedDecl(Diags, R))
8153  return nullptr;
8154 
8155  NamedDecl *ShadowedDecl = R.getFoundDecl();
8156  return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8157 }
8158 
8159 /// Return the declaration shadowed by the given variable \p D, or null
8160 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8162  const LookupResult &R) {
8163  if (!shouldWarnIfShadowedDecl(Diags, R))
8164  return nullptr;
8165 
8166  NamedDecl *ShadowedDecl = R.getFoundDecl();
8167  return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8168  : nullptr;
8169 }
8170 
8171 /// Diagnose variable or built-in function shadowing. Implements
8172 /// -Wshadow.
8173 ///
8174 /// This method is called whenever a VarDecl is added to a "useful"
8175 /// scope.
8176 ///
8177 /// \param ShadowedDecl the declaration that is shadowed by the given variable
8178 /// \param R the lookup of the name
8179 ///
8180 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8181  const LookupResult &R) {
8182  DeclContext *NewDC = D->getDeclContext();
8183 
8184  if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8185  // Fields are not shadowed by variables in C++ static methods.
8186  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
8187  if (MD->isStatic())
8188  return;
8189 
8190  // Fields shadowed by constructor parameters are a special case. Usually
8191  // the constructor initializes the field with the parameter.
8192  if (isa<CXXConstructorDecl>(NewDC))
8193  if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8194  // Remember that this was shadowed so we can either warn about its
8195  // modification or its existence depending on warning settings.
8196  ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8197  return;
8198  }
8199  }
8200 
8201  if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8202  if (shadowedVar->isExternC()) {
8203  // For shadowing external vars, make sure that we point to the global
8204  // declaration, not a locally scoped extern declaration.
8205  for (auto *I : shadowedVar->redecls())
8206  if (I->isFileVarDecl()) {
8207  ShadowedDecl = I;
8208  break;
8209  }
8210  }
8211 
8212  DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8213 
8214  unsigned WarningDiag = diag::warn_decl_shadow;
8215  SourceLocation CaptureLoc;
8216  if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
8217  isa<CXXMethodDecl>(NewDC)) {
8218  if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8219  if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8220  if (RD->getLambdaCaptureDefault() == LCD_None) {
8221  // Try to avoid warnings for lambdas with an explicit capture list.
8222  const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8223  // Warn only when the lambda captures the shadowed decl explicitly.
8224  CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
8225  if (CaptureLoc.isInvalid())
8226  WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8227  } else {
8228  // Remember that this was shadowed so we can avoid the warning if the
8229  // shadowed decl isn't captured and the warning settings allow it.
8230  cast<LambdaScopeInfo>(getCurFunction())
8231  ->ShadowingDecls.push_back(
8232  {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
8233  return;
8234  }
8235  }
8236 
8237  if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
8238  // A variable can't shadow a local variable in an enclosing scope, if
8239  // they are separated by a non-capturing declaration context.
8240  for (DeclContext *ParentDC = NewDC;
8241  ParentDC && !ParentDC->Equals(OldDC);
8242  ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8243  // Only block literals, captured statements, and lambda expressions
8244  // can capture; other scopes don't.
8245  if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8246  !isLambdaCallOperator(ParentDC)) {
8247  return;
8248  }
8249  }
8250  }
8251  }
8252  }
8253 
8254  // Only warn about certain kinds of shadowing for class members.
8255  if (NewDC && NewDC->isRecord()) {
8256  // In particular, don't warn about shadowing non-class members.
8257  if (!OldDC->isRecord())
8258  return;
8259 
8260  // TODO: should we warn about static data members shadowing
8261  // static data members from base classes?
8262 
8263  // TODO: don't diagnose for inaccessible shadowed members.
8264  // This is hard to do perfectly because we might friend the
8265  // shadowing context, but that's just a false negative.
8266  }
8267 
8268 
8269  DeclarationName Name = R.getLookupName();
8270 
8271  // Emit warning and note.
8272  ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8273  Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8274  if (!CaptureLoc.isInvalid())
8275  Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8276  << Name << /*explicitly*/ 1;
8277  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8278 }
8279 
8280 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8281 /// when these variables are captured by the lambda.
8283  for (const auto &Shadow : LSI->ShadowingDecls) {
8284  const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8285  // Try to avoid the warning when the shadowed decl isn't captured.
8286  SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8287  const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8288  Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8289  ? diag::warn_decl_shadow_uncaptured_local
8290  : diag::warn_decl_shadow)
8291  << Shadow.VD->getDeclName()
8292  << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8293  if (!CaptureLoc.isInvalid())
8294  Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8295  << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8296  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8297  }
8298 }
8299 
8300 /// Check -Wshadow without the advantage of a previous lookup.
8302  if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8303  return;
8304 
8305  LookupResult R(*this, D->getDeclName(), D->getLocation(),
8307  LookupName(R, S);
8308  if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8309  CheckShadow(D, ShadowedDecl, R);
8310 }
8311 
8312 /// Check if 'E', which is an expression that is about to be modified, refers
8313 /// to a constructor parameter that shadows a field.
8315  // Quickly ignore expressions that can't be shadowing ctor parameters.
8316  if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8317  return;
8318  E = E->IgnoreParenImpCasts();
8319  auto *DRE = dyn_cast<DeclRefExpr>(E);
8320  if (!DRE)
8321  return;
8322  const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8323  auto I = ShadowingDecls.find(D);
8324  if (I == ShadowingDecls.end())
8325  return;
8326  const NamedDecl *ShadowedDecl = I->second;
8327  const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8328  Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8329  Diag(D->getLocation(), diag::note_var_declared_here) << D;
8330  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8331 
8332  // Avoid issuing multiple warnings about the same decl.
8333  ShadowingDecls.erase(I);
8334 }
8335 
8336 /// Check for conflict between this global or extern "C" declaration and
8337 /// previous global or extern "C" declarations. This is only used in C++.
8338 template<typename T>
8340  Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8341  assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8342  NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8343 
8344  if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8345  // The common case: this global doesn't conflict with any extern "C"
8346  // declaration.
8347  return false;
8348  }
8349 
8350  if (Prev) {
8351  if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8352  // Both the old and new declarations have C language linkage. This is a
8353  // redeclaration.
8354  Previous.clear();
8355  Previous.addDecl(Prev);
8356  return true;
8357  }
8358 
8359  // This is a global, non-extern "C" declaration, and there is a previous
8360  // non-global extern "C" declaration. Diagnose if this is a variable
8361  // declaration.
8362  if (!isa<VarDecl>(ND))
8363  return false;
8364  } else {
8365  // The declaration is extern "C". Check for any declaration in the
8366  // translation unit which might conflict.
8367  if (IsGlobal) {
8368  // We have already performed the lookup into the translation unit.
8369  IsGlobal = false;
8370  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8371  I != E; ++I) {
8372  if (isa<VarDecl>(*I)) {
8373  Prev = *I;
8374  break;
8375  }
8376  }
8377  } else {
8379  S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8380  for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8381  I != E; ++I) {
8382  if (isa<VarDecl>(*I)) {
8383  Prev = *I;
8384  break;
8385  }
8386  // FIXME: If we have any other entity with this name in global scope,
8387  // the declaration is ill-formed, but that is a defect: it breaks the
8388  // 'stat' hack, for instance. Only variables can have mangled name
8389  // clashes with extern "C" declarations, so only they deserve a
8390  // diagnostic.
8391  }
8392  }
8393 
8394  if (!Prev)
8395  return false;
8396  }
8397 
8398  // Use the first declaration's location to ensure we point at something which
8399  // is lexically inside an extern "C" linkage-spec.
8400  assert(Prev && "should have found a previous declaration to diagnose");
8401  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8402  Prev = FD->getFirstDecl();
8403  else
8404  Prev = cast<VarDecl>(Prev)->getFirstDecl();
8405 
8406  S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8407  << IsGlobal << ND;
8408  S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8409  << IsGlobal;
8410  return false;
8411 }
8412 
8413 /// Apply special rules for handling extern "C" declarations. Returns \c true
8414 /// if we have found that this is a redeclaration of some prior entity.
8415 ///
8416 /// Per C++ [dcl.link]p6:
8417 /// Two declarations [for a function or variable] with C language linkage
8418 /// with the same name that appear in different scopes refer to the same
8419 /// [entity]. An entity with C language linkage shall not be declared with
8420 /// the same name as an entity in global scope.
8421 template<typename T>
8422 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8424  if (!S.getLangOpts().CPlusPlus) {
8425  // In C, when declaring a global variable, look for a corresponding 'extern'
8426  // variable declared in function scope. We don't need this in C++, because
8427  // we find local extern decls in the surrounding file-scope DeclContext.
8428  if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8429  if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8430  Previous.clear();
8431  Previous.addDecl(Prev);
8432  return true;
8433  }
8434  }
8435  return false;
8436  }
8437 
8438  // A declaration in the translation unit can conflict with an extern "C"
8439  // declaration.
8440  if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8441  return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8442 
8443  // An extern "C" declaration can conflict with a declaration in the
8444  // translation unit or can be a redeclaration of an extern "C" declaration
8445  // in another scope.
8446  if (isIncompleteDeclExternC(S,ND))
8447  return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8448 
8449  // Neither global nor extern "C": nothing to do.
8450  return false;
8451 }
8452 
8454  // If the decl is already known invalid, don't check it.
8455  if (NewVD->isInvalidDecl())
8456  return;
8457 
8458  QualType T = NewVD->getType();
8459 
8460  // Defer checking an 'auto' type until its initializer is attached.
8461  if (T->isUndeducedType())
8462  return;
8463 
8464  if (NewVD->hasAttrs())
8465  CheckAlignasUnderalignment(NewVD);
8466 
8467  if (T->isObjCObjectType()) {
8468  Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8469  << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8470  T = Context.getObjCObjectPointerType(T);
8471  NewVD->setType(T);
8472  }
8473 
8474  // Emit an error if an address space was applied to decl with local storage.
8475  // This includes arrays of objects with address space qualifiers, but not
8476  // automatic variables that point to other address spaces.
8477  // ISO/IEC TR 18037 S5.1.2
8478  if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8480  Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8481  NewVD->setInvalidDecl();
8482  return;
8483  }
8484 
8485  // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8486  // scope.
8487  if (getLangOpts().OpenCLVersion == 120 &&
8488  !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8489  getLangOpts()) &&
8490  NewVD->isStaticLocal()) {
8491  Diag(NewVD->getLocation(), diag::err_static_function_scope);
8492  NewVD->setInvalidDecl();
8493  return;
8494  }
8495 
8496  if (getLangOpts().OpenCL) {
8497  if (!diagnoseOpenCLTypes(*this, NewVD))
8498  return;
8499 
8500  // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8501  if (NewVD->hasAttr<BlocksAttr>()) {
8502  Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8503  return;
8504  }
8505 
8506  if (T->isBlockPointerType()) {
8507  // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8508  // can't use 'extern' storage class.
8509  if (!T.isConstQualified()) {
8510  Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8511  << 0 /*const*/;
8512  NewVD->setInvalidDecl();
8513  return;
8514  }
8515  if (NewVD->hasExternalStorage()) {
8516  Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8517  NewVD->setInvalidDecl();
8518  return;
8519  }
8520  }
8521 
8522  // FIXME: Adding local AS in C++ for OpenCL might make sense.
8523  if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8524  NewVD->hasExternalStorage()) {
8525  if (!T->isSamplerT() && !T->isDependentType() &&
8528  getOpenCLOptions().areProgramScopeVariablesSupported(
8529  getLangOpts())))) {
8530  int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8531  if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8532  Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8533  << Scope << "global or constant";
8534  else
8535  Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8536  << Scope << "constant";
8537  NewVD->setInvalidDecl();
8538  return;
8539  }
8540  } else {
8542  Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8543  << 1 /*is any function*/ << "global";
8544  NewVD->setInvalidDecl();
8545  return;
8546  }
8549  FunctionDecl *FD = getCurFunctionDecl();
8550  // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8551  // in functions.
8552  if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8554  Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8555  << 0 /*non-kernel only*/ << "constant";
8556  else
8557  Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8558  << 0 /*non-kernel only*/ << "local";
8559  NewVD->setInvalidDecl();
8560  return;
8561  }
8562  // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8563  // in the outermost scope of a kernel function.
8564  if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8565  if (!getCurScope()->isFunctionScope()) {
8567  Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8568  << "constant";
8569  else
8570  Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8571  << "local";
8572  NewVD->setInvalidDecl();
8573  return;
8574  }
8575  }
8576  } else if (T.getAddressSpace() != LangAS::opencl_private &&
8577  // If we are parsing a template we didn't deduce an addr
8578  // space yet.
8580  // Do not allow other address spaces on automatic variable.
8581  Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8582  NewVD->setInvalidDecl();
8583  return;
8584  }
8585  }
8586  }
8587 
8588  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8589  && !NewVD->hasAttr<BlocksAttr>()) {
8590  if (getLangOpts().getGC() != LangOptions::NonGC)
8591  Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8592  else {
8593  assert(!getLangOpts().ObjCAutoRefCount);
8594  Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8595  }
8596  }
8597 
8598  bool isVM = T->isVariablyModifiedType();
8599  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8600  NewVD->hasAttr<BlocksAttr>())
8601  setFunctionHasBranchProtectedScope();
8602 
8603  if ((isVM && NewVD->hasLinkage()) ||
8604  (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8605  bool SizeIsNegative;
8606  llvm::APSInt Oversized;
8608  NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8609  QualType FixedT;
8610  if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8611  FixedT = FixedTInfo->getType();
8612  else if (FixedTInfo) {
8613  // Type and type-as-written are canonically different. We need to fix up
8614  // both types separately.
8615  FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8616  Oversized);
8617  }
8618  if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8619  const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8620  // FIXME: This won't give the correct result for
8621  // int a[10][n];
8622  SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8623 
8624  if (NewVD->isFileVarDecl())
8625  Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8626  << SizeRange;
8627  else if (NewVD->isStaticLocal())
8628  Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8629  << SizeRange;
8630  else
8631  Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8632  << SizeRange;
8633  NewVD->setInvalidDecl();
8634  return;
8635  }
8636 
8637  if (!FixedTInfo) {
8638  if (NewVD->isFileVarDecl())
8639  Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8640  else
8641  Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8642  NewVD->setInvalidDecl();
8643  return;
8644  }
8645 
8646  Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8647  NewVD->setType(FixedT);
8648  NewVD->setTypeSourceInfo(FixedTInfo);
8649  }
8650 
8651  if (T->isVoidType()) {
8652  // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8653  // of objects and functions.
8654  if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8655  Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8656  << T;
8657  NewVD->setInvalidDecl();
8658  return;
8659  }
8660  }
8661 
8662  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8663  Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8664  NewVD->setInvalidDecl();
8665  return;
8666  }
8667 
8668  if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8669  Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8670  NewVD->setInvalidDecl();
8671  return;
8672  }
8673 
8674  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8675  Diag(NewVD->getLocation(), diag::err_block_on_vm);
8676  NewVD->setInvalidDecl();
8677  return;
8678  }
8679 
8680  if (NewVD->isConstexpr() && !T->isDependentType() &&
8681  RequireLiteralType(NewVD->getLocation(), T,
8682  diag::err_constexpr_var_non_literal)) {
8683  NewVD->setInvalidDecl();
8684  return;
8685  }
8686 
8687  // PPC MMA non-pointer types are not allowed as non-local variable types.
8688  if (Context.getTargetInfo().getTriple().isPPC64() &&
8689  !NewVD->isLocalVarDecl() &&
8690  CheckPPCMMAType(T, NewVD->getLocation())) {
8691  NewVD->setInvalidDecl();
8692  return;
8693  }
8694 
8695  // Check that SVE types are only used in functions with SVE available.
8696  if (T->isSVESizelessBuiltinType() && CurContext->isFunctionOrMethod()) {
8697  const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8698  llvm::StringMap<bool> CallerFeatureMap;
8699  Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8701  "sve", CallerFeatureMap)) {
8702  Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8703  NewVD->setInvalidDecl();
8704  return;
8705  }
8706  }
8707 }
8708 
8709 /// Perform semantic checking on a newly-created variable
8710 /// declaration.
8711 ///
8712 /// This routine performs all of the type-checking required for a
8713 /// variable declaration once it has been built. It is used both to
8714 /// check variables after they have been parsed and their declarators
8715 /// have been translated into a declaration, and to check variables
8716 /// that have been instantiated from a template.
8717 ///
8718 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8719 ///
8720 /// Returns true if the variable declaration is a redeclaration.
8722  CheckVariableDeclarationType(NewVD);
8723 
8724  // If the decl is already known invalid, don't check it.
8725  if (NewVD->isInvalidDecl())
8726  return false;
8727 
8728  // If we did not find anything by this name, look for a non-visible
8729  // extern "C" declaration with the same name.
8730  if (Previous.empty() &&
8732  Previous.setShadowed();
8733 
8734  if (!Previous.empty()) {
8735  MergeVarDecl(NewVD, Previous);
8736  return true;
8737  }
8738  return false;
8739 }
8740 
8741 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8742 /// and if so, check that it's a valid override and remember it.
8745 
8746  // Look for methods in base classes that this method might override.
8747  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8748  /*DetectVirtual=*/false);
8749  auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8750  CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8751  DeclarationName Name = MD->getDeclName();
8752 
8753  if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8754  // We really want to find the base class destructor here.
8755  QualType T = Context.getTypeDeclType(BaseRecord);
8756  CanQualType CT = Context.getCanonicalType(T);
8757  Name = Context.DeclarationNames.getCXXDestructorName(CT);
8758  }
8759 
8760  for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8761  CXXMethodDecl *BaseMD =
8762  dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8763  if (!BaseMD || !BaseMD->isVirtual() ||
8764  IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8765  /*ConsiderCudaAttrs=*/true,
8766  // C++2a [class.virtual]p2 does not consider requires
8767  // clauses when overriding.
8768  /*ConsiderRequiresClauses=*/false))
8769  continue;
8770 
8771  if (Overridden.insert(BaseMD).second) {
8772  MD->addOverriddenMethod(BaseMD);
8773  CheckOverridingFunctionReturnType(MD, BaseMD);
8774  CheckOverridingFunctionAttributes(MD, BaseMD);
8775  CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8776  CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8777  }
8778 
8779  // A method can only override one function from each base class. We
8780  // don't track indirectly overridden methods from bases of bases.
8781  return true;
8782  }
8783 
8784  return false;
8785  };
8786 
8787  DC->lookupInBases(VisitBase, Paths);
8788  return !Overridden.empty();
8789 }
8790 
8791 namespace {
8792  // Struct for holding all of the extra arguments needed by
8793  // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8794  struct ActOnFDArgs {
8795  Scope *S;
8796  Declarator &D;
8797  MultiTemplateParamsArg TemplateParamLists;
8798  bool AddToScope;
8799  };
8800 } // end anonymous namespace
8801 
8802 namespace {
8803 
8804 // Callback to only accept typo corrections that have a non-zero edit distance.
8805 // Also only accept corrections that have the same parent decl.
8806 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8807  public:
8808  DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8810  : Context(Context), OriginalFD(TypoFD),
8811  ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8812 
8813  bool ValidateCandidate(const TypoCorrection &candidate) override {
8814  if (candidate.getEditDistance() == 0)
8815  return false;
8816 
8817  SmallVector<unsigned, 1> MismatchedParams;
8818  for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8819  CDeclEnd = candidate.end();
8820  CDecl != CDeclEnd; ++CDecl) {
8821  FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8822 
8823  if (FD && !FD->hasBody() &&
8824  hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8825  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8826  CXXRecordDecl *Parent = MD->getParent();
8827  if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8828  return true;
8829  } else if (!ExpectedParent) {
8830  return true;
8831  }
8832  }
8833  }
8834 
8835  return false;
8836  }
8837 
8838  std::unique_ptr<CorrectionCandidateCallback> clone() override {
8839  return std::make_unique<DifferentNameValidatorCCC>(*this);
8840  }
8841 
8842  private:
8843  ASTContext &Context;
8844  FunctionDecl *OriginalFD;
8845  CXXRecordDecl *ExpectedParent;
8846 };
8847 
8848 } // end anonymous namespace
8849 
8851  TypoCorrectedFunctionDefinitions.insert(F);
8852 }
8853 
8854 /// Generate diagnostics for an invalid function redeclaration.
8855 ///
8856 /// This routine handles generating the diagnostic messages for an invalid
8857 /// function redeclaration, including finding possible similar declarations
8858 /// or performing typo correction if there are no previous declarations with
8859 /// the same name.
8860 ///
8861 /// Returns a NamedDecl iff typo correction was performed and substituting in
8862 /// the new declaration name does not cause new errors.
8864  Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8865  ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8866  DeclarationName Name = NewFD->getDeclName();
8867  DeclContext *NewDC = NewFD->getDeclContext();
8868  SmallVector<unsigned, 1> MismatchedParams;
8870  TypoCorrection Correction;
8871  bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8872  unsigned DiagMsg =
8873  IsLocalFriend ? diag::err_no_matching_local_friend :
8874  NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8875  diag::err_member_decl_does_not_match;
8876  LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8877  IsLocalFriend ? Sema::LookupLocalFriendName
8880 
8881  NewFD->setInvalidDecl();
8882  if (IsLocalFriend)
8883  SemaRef.LookupName(Prev, S);
8884  else
8885  SemaRef.LookupQualifiedName(Prev, NewDC);
8886  assert(!Prev.isAmbiguous() &&
8887  "Cannot have an ambiguity in previous-declaration lookup");
8888  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8889  DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8890  MD ? MD->getParent() : nullptr);
8891  if (!Prev.empty()) {
8892  for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8893  Func != FuncEnd; ++Func) {
8894  FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8895  if (FD &&
8896  hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8897  // Add 1 to the index so that 0 can mean the mismatch didn't
8898  // involve a parameter
8899  unsigned ParamNum =
8900  MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8901  NearMatches.push_back(std::make_pair(FD, ParamNum));
8902  }
8903  }
8904  // If the qualified name lookup yielded nothing, try typo correction
8905  } else if ((Correction = SemaRef.CorrectTypo(
8906  Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8907  &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8908  IsLocalFriend ? nullptr : NewDC))) {
8909  // Set up everything for the call to ActOnFunctionDeclarator
8910  ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8911  ExtraArgs.D.getIdentifierLoc());
8912  Previous.clear();
8913  Previous.setLookupName(Correction.getCorrection());
8914  for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8915  CDeclEnd = Correction.end();
8916  CDecl != CDeclEnd; ++CDecl) {
8917  FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8918  if (FD && !FD->hasBody() &&
8919  hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8920  Previous.addDecl(FD);
8921  }
8922  }
8923  bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8924 
8925  NamedDecl *Result;
8926  // Retry building the function declaration with the new previous
8927  // declarations, and with errors suppressed.
8928  {
8929  // Trap errors.
8930  Sema::SFINAETrap Trap(SemaRef);
8931 
8932  // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8933  // pieces need to verify the typo-corrected C++ declaration and hopefully
8934  // eliminate the need for the parameter pack ExtraArgs.
8935  Result = SemaRef.ActOnFunctionDeclarator(
8936  ExtraArgs.S, ExtraArgs.D,
8937  Correction.getCorrectionDecl()->getDeclContext(),
8938  NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8939  ExtraArgs.AddToScope);
8940 
8941  if (Trap.hasErrorOccurred())
8942  Result = nullptr;
8943  }
8944 
8945  if (Result) {
8946  // Determine which correction we picked.
8947  Decl *Canonical = Result->getCanonicalDecl();
8948  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8949  I != E; ++I)
8950  if ((*I)->getCanonicalDecl() == Canonical)
8951  Correction.setCorrectionDecl(*I);
8952 
8953  // Let Sema know about the correction.
8954  SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8955  SemaRef.diagnoseTypo(
8956  Correction,
8957  SemaRef.PDiag(IsLocalFriend
8958  ? diag::err_no_matching_local_friend_suggest
8959  : diag::err_member_decl_does_not_match_suggest)
8960  << Name << NewDC << IsDefinition);
8961  return Result;
8962  }
8963 
8964  // Pretend the typo correction never occurred
8965  ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8966  ExtraArgs.D.getIdentifierLoc());
8967  ExtraArgs.D.setRedeclaration(wasRedeclaration);
8968  Previous.clear();
8969  Previous.setLookupName(Name);
8970  }
8971 
8972  SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8973  << Name << NewDC << IsDefinition << NewFD->getLocation();
8974 
8975  bool NewFDisConst = false;
8976  if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8977  NewFDisConst = NewMD->isConst();
8978 
8979  for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8980  NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8981  NearMatch != NearMatchEnd; ++NearMatch) {
8982  FunctionDecl *FD = NearMatch->first;
8983  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8984  bool FDisConst = MD && MD->isConst();
8985  bool IsMember = MD || !IsLocalFriend;
8986 
8987  // FIXME: These notes are poorly worded for the local friend case.
8988  if (unsigned Idx = NearMatch->second) {
8989  ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8990  SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8991  if (Loc.isInvalid()) Loc = FD->getLocation();
8992  SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8993  : diag::note_local_decl_close_param_match)
8994  << Idx << FDParam->getType()
8995  << NewFD->getParamDecl(Idx - 1)->getType();
8996  } else if (FDisConst != NewFDisConst) {
8997  SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8998  << NewFDisConst << FD->getSourceRange().getEnd()
8999  << (NewFDisConst
9000  ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
9001  .getConstQualifierLoc())
9002  : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
9003  .getRParenLoc()
9004  .getLocWithOffset(1),
9005  " const"));
9006  } else
9007  SemaRef.Diag(FD->getLocation(),
9008  IsMember ? diag::note_member_def_close_match
9009  : diag::note_local_decl_close_match);
9010  }
9011  return nullptr;
9012 }
9013 
9015  switch (D.getDeclSpec().getStorageClassSpec()) {
9016  default: llvm_unreachable("Unknown storage class!");
9017  case DeclSpec::SCS_auto:
9019  case DeclSpec::SCS_mutable:
9020  SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9021  diag::err_typecheck_sclass_func);
9023  D.setInvalidType();
9024  break;
9025  case DeclSpec::SCS_unspecified: break;
9026  case DeclSpec::SCS_extern:
9028  return SC_None;
9029  return SC_Extern;
9030  case DeclSpec::SCS_static: {
9031  if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9032  // C99 6.7.1p5:
9033  // The declaration of an identifier for a function that has
9034  // block scope shall have no explicit storage-class specifier
9035  // other than extern
9036  // See also (C++ [dcl.stc]p4).
9037  SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9038  diag::err_static_block_func);
9039  break;
9040  } else
9041  return SC_Static;
9042  }
9044  }
9045 
9046  // No explicit storage class has already been returned
9047  return SC_None;
9048 }
9049 
9051  DeclContext *DC, QualType &R,
9052  TypeSourceInfo *TInfo,
9053  StorageClass SC,
9054  bool &IsVirtualOkay) {
9055  DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9056  DeclarationName Name = NameInfo.getName();
9057 
9058  FunctionDecl *NewFD = nullptr;
9059  bool isInline = D.getDeclSpec().isInlineSpecified();
9060 
9061  if (!SemaRef.getLangOpts().CPlusPlus) {
9062  // Determine whether the function was written with a prototype. This is
9063  // true when:
9064  // - there is a prototype in the declarator, or
9065  // - the type R of the function is some kind of typedef or other non-
9066  // attributed reference to a type name (which eventually refers to a
9067  // function type). Note, we can't always look at the adjusted type to
9068  // check this case because attributes may cause a non-function
9069  // declarator to still have a function type. e.g.,
9070  // typedef void func(int a);
9071  // __attribute__((noreturn)) func other_func; // This has a prototype
9072  bool HasPrototype =
9074  (D.getDeclSpec().isTypeRep() &&
9077  assert(
9078  (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9079  "Strict prototypes are required");
9080 
9081  NewFD = FunctionDecl::Create(
9082  SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9083  SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9085  /*TrailingRequiresClause=*/nullptr);
9086  if (D.isInvalidType())
9087  NewFD->setInvalidDecl();
9088 
9089  return NewFD;
9090  }
9091 
9093 
9094  ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9095  if (ConstexprKind == ConstexprSpecKind::Constinit) {
9096  SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9097  diag::err_constexpr_wrong_decl_kind)
9098  << static_cast<int>(ConstexprKind);
9099  ConstexprKind = ConstexprSpecKind::Unspecified;
9101  }
9102  Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9103 
9104  // Check that the return type is not an abstract class type.
9105  // For record types, this is done by the AbstractClassUsageDiagnoser once
9106  // the class has been completely parsed.
9107  if (!DC->isRecord() &&
9108  SemaRef.RequireNonAbstractType(
9110  diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
9111  D.setInvalidType();
9112 
9113  if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9114  // This is a C++ constructor declaration.
9115  assert(DC->isRecord() &&
9116  "Constructors can only be declared in a member context");
9117 
9118  R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9120  SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9122  isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9123  InheritedConstructor(), TrailingRequiresClause);
9124 
9125  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9126  // This is a C++ destructor declaration.
9127  if (DC->isRecord()) {
9128  R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9129  CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9131  SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9132  SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9133  /*isImplicitlyDeclared=*/false, ConstexprKind,
9134  TrailingRequiresClause);
9135  // User defined destructors start as not selected if the class definition is still
9136  // not done.
9137  if (Record->isBeingDefined())
9138  NewDD->setIneligibleOrNotSelected(true);
9139 
9140  // If the destructor needs an implicit exception specification, set it
9141  // now. FIXME: It'd be nice to be able to create the right type to start
9142  // with, but the type needs to reference the destructor declaration.
9143  if (SemaRef.getLangOpts().CPlusPlus11)
9144  SemaRef.AdjustDestructorExceptionSpec(NewDD);
9145 
9146  IsVirtualOkay = true;
9147  return NewDD;
9148 
9149  } else {
9150  SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9151  D.setInvalidType();
9152 
9153  // Create a FunctionDecl to satisfy the function definition parsing
9154  // code path.
9155  return FunctionDecl::Create(
9156  SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9157  TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9158  /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9159  }
9160 
9161  } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9162  if (!DC->isRecord()) {
9163  SemaRef.Diag(D.getIdentifierLoc(),
9164  diag::err_conv_function_not_member);
9165  return nullptr;
9166  }
9167 
9168  SemaRef.CheckConversionDeclarator(D, R, SC);
9169  if (D.isInvalidType())
9170  return nullptr;
9171 
9172  IsVirtualOkay = true;
9174  SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9175  TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9176  ExplicitSpecifier, ConstexprKind, SourceLocation(),
9177  TrailingRequiresClause);
9178 
9179  } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9180  if (TrailingRequiresClause)
9181  SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9182  diag::err_trailing_requires_clause_on_deduction_guide)
9183  << TrailingRequiresClause->getSourceRange();
9184  SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
9185 
9186  return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
9187  ExplicitSpecifier, NameInfo, R, TInfo,
9188  D.getEndLoc());
9189  } else if (DC->isRecord()) {
9190  // If the name of the function is the same as the name of the record,
9191  // then this must be an invalid constructor that has a return type.
9192  // (The parser checks for a return type and makes the declarator a
9193  // constructor if it has no return type).
9194  if (Name.getAsIdentifierInfo() &&
9195  Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9196  SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9198  << SourceRange(D.getIdentifierLoc());
9199  return nullptr;
9200  }
9201 
9202  // This is a C++ method declaration.
9204  SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9205  TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9206  ConstexprKind, SourceLocation(), TrailingRequiresClause);
9207  IsVirtualOkay = !Ret->isStatic();
9208  return Ret;
9209  } else {
9210  bool isFriend =
9211  SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9212  if (!isFriend && SemaRef.CurContext->isRecord())
9213  return nullptr;
9214 
9215  // Determine whether the function was written with a
9216  // prototype. This true when:
9217  // - we're in C++ (where every function has a prototype),
9218  return FunctionDecl::Create(
9219  SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9220  SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9221  true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9222  }
9223 }
9224 
9232 };
9233 
9235  // Size dependent types are just typedefs to normal integer types
9236  // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9237  // integers other than by their names.
9238  StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9239 
9240  // Remove typedefs one by one until we reach a typedef
9241  // for a size dependent type.
9242  QualType DesugaredTy = Ty;
9243  do {
9244  ArrayRef<StringRef> Names(SizeTypeNames);
9245  auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9246  if (Names.end() != Match)
9247  return true;
9248 
9249  Ty = DesugaredTy;
9250  DesugaredTy = Ty.getSingleStepDesugaredType(C);
9251  } while (DesugaredTy != Ty);
9252 
9253  return false;
9254 }
9255 
9257  if (PT->isDependentType())
9258  return InvalidKernelParam;
9259 
9260  if (PT->isPointerType() || PT->isReferenceType()) {
9261  QualType PointeeType = PT->getPointeeType();
9262  if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9263  PointeeType.getAddressSpace() == LangAS::opencl_private ||
9264  PointeeType.getAddressSpace() == LangAS::Default)
9266 
9267  if (PointeeType->isPointerType()) {
9268  // This is a pointer to pointer parameter.
9269  // Recursively check inner type.
9270  OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9271  if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9272  ParamKind == InvalidKernelParam)
9273  return ParamKind;
9274 
9275  return PtrPtrKernelParam;
9276  }
9277 
9278  // C++ for OpenCL v1.0 s2.4:
9279  // Moreover the types used in parameters of the kernel functions must be:
9280  // Standard layout types for pointer parameters. The same applies to
9281  // reference if an implementation supports them in kernel parameters.
9282  if (S.getLangOpts().OpenCLCPlusPlus &&
9284  "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9285  auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9286  bool IsStandardLayoutType = true;
9287  if (CXXRec) {
9288  // If template type is not ODR-used its definition is only available
9289  // in the template definition not its instantiation.
9290  // FIXME: This logic doesn't work for types that depend on template
9291  // parameter (PR58590).
9292  if (!CXXRec->hasDefinition())
9293  CXXRec = CXXRec->getTemplateInstantiationPattern();
9294  if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9295  IsStandardLayoutType = false;
9296  }
9297  if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9298  !IsStandardLayoutType)
9299  return InvalidKernelParam;
9300  }
9301 
9302  return PtrKernelParam;
9303  }
9304 
9305  // OpenCL v1.2 s6.9.k:
9306  // Arguments to kernel functions in a program cannot be declared with the
9307  // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9308  // uintptr_t or a struct and/or union that contain fields declared to be one
9309  // of these built-in scalar types.
9311  return InvalidKernelParam;
9312 
9313  if (PT->isImageType())
9314  return PtrKernelParam;
9315 
9316  if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9317  return InvalidKernelParam;
9318 
9319  // OpenCL extension spec v1.2 s9.5:
9320  // This extension adds support for half scalar and vector types as built-in
9321  // types that can be used for arithmetic operations, conversions etc.
9322  if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9323  PT->isHalfType())
9324  return InvalidKernelParam;
9325 
9326  // Look into an array argument to check if it has a forbidden type.
9327  if (PT->isArrayType()) {
9328  const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9329  // Call ourself to check an underlying type of an array. Since the
9330  // getPointeeOrArrayElementType returns an innermost type which is not an
9331  // array, this recursive call only happens once.
9332  return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9333  }
9334 
9335  // C++ for OpenCL v1.0 s2.4:
9336  // Moreover the types used in parameters of the kernel functions must be:
9337  // Trivial and standard-layout types C++17 [basic.types] (plain old data
9338  // types) for parameters passed by value;
9339  if (S.getLangOpts().OpenCLCPlusPlus &&
9341  "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9342  !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9343  return InvalidKernelParam;
9344 
9345  if (PT->isRecordType())
9346  return RecordKernelParam;
9347 
9348  return ValidKernelParam;
9349 }
9350 
9352  Sema &S,
9353  Declarator &D,
9354  ParmVarDecl *Param,
9355  llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9356  QualType PT = Param->getType();
9357 
9358  // Cache the valid types we encounter to avoid rechecking structs that are
9359  // used again
9360  if (ValidTypes.count(PT.getTypePtr()))
9361  return;
9362 
9363  switch (getOpenCLKernelParameterType(S, PT)) {
9364  case PtrPtrKernelParam:
9365  // OpenCL v3.0 s6.11.a:
9366  // A kernel function argument cannot be declared as a pointer to a pointer
9367  // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9368  if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
9369  S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9370  D.setInvalidType();
9371  return;
9372  }
9373 
9374  ValidTypes.insert(PT.getTypePtr());
9375  return;
9376 
9378  // OpenCL v1.0 s6.5:
9379  // __kernel function arguments declared to be a pointer of a type can point
9380  // to one of the following address spaces only : __global, __local or
9381  // __constant.
9382  S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9383  D.setInvalidType();
9384  return;
9385 
9386  // OpenCL v1.2 s6.9.k:
9387  // Arguments to kernel functions in a program cannot be declared with the
9388  // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9389  // uintptr_t or a struct and/or union that contain fields declared to be
9390  // one of these built-in scalar types.
9391 
9392  case InvalidKernelParam:
9393  // OpenCL v1.2 s6.8 n:
9394  // A kernel function argument cannot be declared
9395  // of event_t type.
9396  // Do not diagnose half type since it is diagnosed as invalid argument
9397  // type for any function elsewhere.
9398  if (!PT->isHalfType()) {
9399  S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9400 
9401  // Explain what typedefs are involved.
9402  const TypedefType *Typedef = nullptr;
9403  while ((Typedef = PT->getAs<TypedefType>())) {
9404  SourceLocation Loc = Typedef->getDecl()->getLocation();
9405  // SourceLocation may be invalid for a built-in type.
9406  if (Loc.isValid())
9407  S.Diag(Loc, diag::note_entity_declared_at) << PT;
9408  PT = Typedef->desugar();
9409  }
9410  }
9411 
9412  D.setInvalidType();
9413  return;
9414 
9415  case PtrKernelParam:
9416  case ValidKernelParam:
9417  ValidTypes.insert(PT.getTypePtr());
9418  return;
9419 
9420  case RecordKernelParam:
9421  break;
9422  }
9423 
9424  // Track nested structs we will inspect
9425  SmallVector<const Decl *, 4> VisitStack;
9426 
9427  // Track where we are in the nested structs. Items will migrate from
9428  // VisitStack to HistoryStack as we do the DFS for bad field.
9429  SmallVector<const FieldDecl *, 4> HistoryStack;
9430  HistoryStack.push_back(nullptr);
9431 
9432  // At this point we already handled everything except of a RecordType or
9433  // an ArrayType of a RecordType.
9434  assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9435  const RecordType *RecTy =
9437  const RecordDecl *OrigRecDecl = RecTy->getDecl();
9438 
9439  VisitStack.push_back(RecTy->getDecl());
9440  assert(VisitStack.back() && "First decl null?");
9441 
9442  do {
9443  const Decl *Next = VisitStack.pop_back_val();
9444  if (!Next) {
9445  assert(!HistoryStack.empty());
9446  // Found a marker, we have gone up a level
9447  if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9448  ValidTypes.insert(Hist->getType().getTypePtr());
9449 
9450  continue;
9451  }
9452 
9453  // Adds everything except the original parameter declaration (which is not a
9454  // field itself) to the history stack.
9455  const RecordDecl *RD;
9456  if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9457  HistoryStack.push_back(Field);
9458 
9459  QualType FieldTy = Field->getType();
9460  // Other field types (known to be valid or invalid) are handled while we
9461  // walk around RecordDecl::fields().
9462  assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9463  "Unexpected type.");
9464  const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9465 
9466  RD = FieldRecTy->castAs<RecordType>()->getDecl();
9467  } else {
9468  RD = cast<RecordDecl>(Next);
9469  }
9470 
9471  // Add a null marker so we know when we've gone back up a level
9472  VisitStack.push_back(nullptr);
9473 
9474  for (const auto *FD : RD->fields()) {
9475  QualType QT = FD->getType();
9476 
9477  if (ValidTypes.count(QT.getTypePtr()))
9478  continue;
9479 
9480  OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9481  if (ParamType == ValidKernelParam)
9482  continue;
9483 
9484  if (ParamType == RecordKernelParam) {
9485  VisitStack.push_back(FD);
9486  continue;
9487  }
9488 
9489  // OpenCL v1.2 s6.9.p:
9490  // Arguments to kernel functions that are declared to be a struct or union
9491  // do not allow OpenCL objects to be passed as elements of the struct or
9492  // union.
9493  if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9494  ParamType == InvalidAddrSpacePtrKernelParam) {
9495  S.Diag(Param->getLocation(),
9496  diag::err_record_with_pointers_kernel_param)
9497  << PT->isUnionType()
9498  << PT;
9499  } else {
9500  S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9501  }
9502 
9503  S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9504  << OrigRecDecl->getDeclName();
9505 
9506  // We have an error, now let's go back up through history and show where
9507  // the offending field came from
9509  I = HistoryStack.begin() + 1,
9510  E = HistoryStack.end();
9511  I != E; ++I) {
9512  const FieldDecl *OuterField = *I;
9513  S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9514  << OuterField->getType();
9515  }
9516 
9517  S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9518  << QT->isPointerType()
9519  << QT;
9520  D.setInvalidType();
9521  return;
9522  }
9523  } while (!VisitStack.empty());
9524 }
9525 
9526 /// Find the DeclContext in which a tag is implicitly declared if we see an
9527 /// elaborated type specifier in the specified context, and lookup finds
9528 /// nothing.
9530  while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9531  DC = DC->getParent();
9532  return DC;
9533 }
9534 
9535 /// Find the Scope in which a tag is implicitly declared if we see an
9536 /// elaborated type specifier in the specified context, and lookup finds
9537 /// nothing.
9538 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9539  while (S->isClassScope() ||
9540  (LangOpts.CPlusPlus &&
9541  S->isFunctionPrototypeScope()) ||
9542  ((S->getFlags() & Scope::DeclScope) == 0) ||
9543  (S->getEntity() && S->getEntity()->isTransparentContext()))
9544  S = S->getParent();
9545  return S;
9546 }
9547 
9548 /// Determine whether a declaration matches a known function in namespace std.
9549 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9550  unsigned BuiltinID) {
9551  switch (BuiltinID) {
9552  case Builtin::BI__GetExceptionInfo:
9553  // No type checking whatsoever.
9554  return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9555 
9556  case Builtin::BIaddressof:
9557  case Builtin::BI__addressof:
9558  case Builtin::BIforward:
9559  case Builtin::BIforward_like:
9560  case Builtin::BImove:
9561  case Builtin::BImove_if_noexcept:
9562  case Builtin::BIas_const: {
9563  // Ensure that we don't treat the algorithm
9564  // OutputIt std::move(InputIt, InputIt, OutputIt)
9565  // as the builtin std::move.
9566  const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9567  return FPT->getNumParams() == 1 && !FPT->isVariadic();
9568  }
9569 
9570  default:
9571  return false;
9572  }
9573 }
9574 
9575 NamedDecl*
9578  MultiTemplateParamsArg TemplateParamListsRef,
9579  bool &AddToScope) {
9580  QualType R = TInfo->getType();
9581 
9582  assert(R->isFunctionType());
9584  Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9585 
9586  SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9587  llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9589  if (!TemplateParamLists.empty() &&
9590  Invented->getDepth() == TemplateParamLists.back()->getDepth())
9591  TemplateParamLists.back() = Invented;
9592  else
9593  TemplateParamLists.push_back(Invented);
9594  }
9595 
9596  // TODO: consider using NameInfo for diagnostic.
9597  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9598  DeclarationName Name = NameInfo.getName();
9599  StorageClass SC = getFunctionStorageClass(*this, D);
9600 
9603  diag::err_invalid_thread)
9604  << DeclSpec::getSpecifierName(TSCS);
9605 
9607  adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9608  D.getIdentifierLoc());
9609 
9610  bool isFriend = false;
9611  FunctionTemplateDecl *FunctionTemplate = nullptr;
9612  bool isMemberSpecialization = false;
9613  bool isFunctionTemplateSpecialization = false;
9614 
9615  bool isDependentClassScopeExplicitSpecialization = false;
9616  bool HasExplicitTemplateArgs = false;
9617  TemplateArgumentListInfo TemplateArgs;
9618 
9619  bool isVirtualOkay = false;
9620 
9621  DeclContext *OriginalDC = DC;
9622  bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9623 
9624  FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9625  isVirtualOkay);
9626  if (!NewFD) return nullptr;
9627 
9628  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9630 
9631  // Set the lexical context. If this is a function-scope declaration, or has a
9632  // C++ scope specifier, or is the object of a friend declaration, the lexical
9633  // context will be different from the semantic context.
9634  NewFD->setLexicalDeclContext(CurContext);
9635 
9636  if (IsLocalExternDecl)
9637  NewFD->setLocalExternDecl();
9638 
9639  if (getLangOpts().CPlusPlus) {
9640  // The rules for implicit inlines changed in C++20 for methods and friends
9641  // with an in-class definition (when such a definition is not attached to
9642  // the global module). User-specified 'inline' overrides this (set when
9643  // the function decl is created above).
9644  // FIXME: We need a better way to separate C++ standard and clang modules.
9645  bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9646  !NewFD->getOwningModule() ||
9647  NewFD->getOwningModule()->isGlobalModule() ||
9648  NewFD->getOwningModule()->isHeaderLikeModule();
9649  bool isInline = D.getDeclSpec().isInlineSpecified();
9650  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9651  bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9652  isFriend = D.getDeclSpec().isFriendSpecified();
9653  if (isFriend && !isInline && D.isFunctionDefinition()) {
9654  // Pre-C++20 [class.friend]p5
9655  // A function can be defined in a friend declaration of a
9656  // class . . . . Such a function is implicitly inline.
9657  // Post C++20 [class.friend]p7
9658  // Such a function is implicitly an inline function if it is attached
9659  // to the global module.
9660  NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9661  }
9662 
9663  // If this is a method defined in an __interface, and is not a constructor
9664  // or an overloaded operator, then set the pure flag (isVirtual will already
9665  // return true).
9666  if (const CXXRecordDecl *Parent =
9667  dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9668  if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9669  NewFD->setPure(true);
9670 
9671  // C++ [class.union]p2
9672  // A union can have member functions, but not virtual functions.
9673  if (isVirtual && Parent->isUnion()) {
9674  Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9675  NewFD->setInvalidDecl();
9676  }
9677  if ((Parent->isClass() || Parent->isStruct()) &&
9678  Parent->hasAttr<SYCLSpecialClassAttr>() &&
9679  NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9680  NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9681  if (auto *Def = Parent->getDefinition())
9682  Def->setInitMethod(true);
9683  }
9684  }
9685 
9686  SetNestedNameSpecifier(*this, NewFD, D);
9687  isMemberSpecialization = false;
9688  isFunctionTemplateSpecialization = false;
9689  if (D.isInvalidType())
9690  NewFD->setInvalidDecl();
9691 
9692  // Match up the template parameter lists with the scope specifier, then
9693  // determine whether we have a template or a template specialization.
9694  bool Invalid = false;
9695  TemplateParameterList *TemplateParams =
9696  MatchTemplateParametersToScopeSpecifier(
9698  D.getCXXScopeSpec(),
9700  ? D.getName().TemplateId
9701  : nullptr,
9702  TemplateParamLists, isFriend, isMemberSpecialization,
9703  Invalid);
9704  if (TemplateParams) {
9705  // Check that we can declare a template here.
9706  if (CheckTemplateDeclScope(S, TemplateParams))
9707  NewFD->setInvalidDecl();
9708 
9709  if (TemplateParams->size() > 0) {
9710  // This is a function template
9711 
9712  // A destructor cannot be a template.
9713  if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9714  Diag(NewFD->getLocation(), diag::err_destructor_template);
9715  NewFD->setInvalidDecl();
9716  }
9717 
9718  // If we're adding a template to a dependent context, we may need to
9719  // rebuilding some of the types used within the template parameter list,
9720  // now that we know what the current instantiation is.
9721  if (DC->isDependentContext()) {
9722  ContextRAII SavedContext(*this, DC);
9723  if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9724  Invalid = true;
9725  }
9726 
9727  FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9728  NewFD->getLocation(),
9729  Name, TemplateParams,
9730  NewFD);
9731  FunctionTemplate->setLexicalDeclContext(CurContext);
9732  NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9733 
9734  // For source fidelity, store the other template param lists.
9735  if (TemplateParamLists.size() > 1) {
9736  NewFD->setTemplateParameterListsInfo(Context,
9737  ArrayRef<TemplateParameterList *>(TemplateParamLists)
9738  .drop_back(1));
9739  }
9740  } else {
9741  // This is a function template specialization.
9742  isFunctionTemplateSpecialization = true;
9743  // For source fidelity, store all the template param lists.
9744  if (TemplateParamLists.size() > 0)
9745  NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9746 
9747  // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9748  if (isFriend) {
9749  // We want to remove the "template<>", found here.
9750  SourceRange RemoveRange = TemplateParams->getSourceRange();
9751 
9752  // If we remove the template<> and the name is not a
9753  // template-id, we're actually silently creating a problem:
9754  // the friend declaration will refer to an untemplated decl,
9755  // and clearly the user wants a template specialization. So
9756  // we need to insert '<>' after the name.
9757  SourceLocation InsertLoc;
9759  InsertLoc = D.getName().getSourceRange().getEnd();
9760  InsertLoc = getLocForEndOfToken(InsertLoc);
9761  }
9762 
9763  Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9764  << Name << RemoveRange
9765  << FixItHint::CreateRemoval(RemoveRange)
9766  << FixItHint::CreateInsertion(InsertLoc, "<>");
9767  Invalid = true;
9768  }
9769  }
9770  } else {
9771  // Check that we can declare a template here.
9772  if (!TemplateParamLists.empty() && isMemberSpecialization &&
9773  CheckTemplateDeclScope(S, TemplateParamLists.back()))
9774  NewFD->setInvalidDecl();
9775 
9776  // All template param lists were matched against the scope specifier:
9777  // this is NOT (an explicit specialization of) a template.
9778  if (TemplateParamLists.size() > 0)
9779  // For source fidelity, store all the template param lists.
9780  NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9781  }
9782 
9783  if (Invalid) {
9784  NewFD->setInvalidDecl();
9785  if (FunctionTemplate)
9786  FunctionTemplate->setInvalidDecl();
9787  }
9788 
9789  // C++ [dcl.fct.spec]p5:
9790  // The virtual specifier shall only be used in declarations of
9791  // nonstatic class member functions that appear within a
9792  // member-specification of a class declaration; see 10.3.
9793  //
9794  if (isVirtual && !NewFD->isInvalidDecl()) {
9795  if (!isVirtualOkay) {
9797  diag::err_virtual_non_function);
9798  } else if (!CurContext->isRecord()) {
9799  // 'virtual' was specified outside of the class.
9801  diag::err_virtual_out_of_class)
9803  } else if (NewFD->getDescribedFunctionTemplate()) {
9804  // C++ [temp.mem]p3:
9805  // A member function template shall not be virtual.
9807  diag::err_virtual_member_function_template)
9809  } else {
9810  // Okay: Add virtual to the method.
9811  NewFD->setVirtualAsWritten(true);
9812  }
9813 
9814  if (getLangOpts().CPlusPlus14 &&
9815  NewFD->getReturnType()->isUndeducedType())
9816  Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9817  }
9818 
9819  if (getLangOpts().CPlusPlus14 &&
9820  (NewFD->isDependentContext() ||
9821  (isFriend && CurContext->isDependentContext())) &&
9822  NewFD->getReturnType()->isUndeducedType()) {
9823  // If the function template is referenced directly (for instance, as a
9824  // member of the current instantiation), pretend it has a dependent type.
9825  // This is not really justified by the standard, but is the only sane
9826  // thing to do.
9827  // FIXME: For a friend function, we have not marked the function as being
9828  // a friend yet, so 'isDependentContext' on the FD doesn't work.
9829  const FunctionProtoType *FPT =
9830  NewFD->getType()->castAs<FunctionProtoType>();
9831  QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9832  NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9833  FPT->getExtProtoInfo()));
9834  }
9835 
9836  // C++ [dcl.fct.spec]p3:
9837  // The inline specifier shall not appear on a block scope function
9838  // declaration.
9839  if (isInline && !NewFD->isInvalidDecl()) {
9840  if (CurContext->isFunctionOrMethod()) {
9841  // 'inline' is not allowed on block scope function declaration.
9843  diag::err_inline_declaration_block_scope) << Name
9845  }
9846  }
9847 
9848  // C++ [dcl.fct.spec]p6:
9849  // The explicit specifier shall be used only in the declaration of a
9850  // constructor or conversion function within its class definition;
9851  // see 12.3.1 and 12.3.2.
9852  if (hasExplicit && !NewFD->isInvalidDecl() &&
9853  !isa<CXXDeductionGuideDecl>(NewFD)) {
9854  if (!CurContext->isRecord()) {
9855  // 'explicit' was specified outside of the class.
9857  diag::err_explicit_out_of_class)
9859  } else if (!isa<CXXConstructorDecl>(NewFD) &&
9860  !isa<CXXConversionDecl>(NewFD)) {
9861  // 'explicit' was specified on a function that wasn't a constructor
9862  // or conversion function.
9864  diag::err_explicit_non_ctor_or_conv_function)
9866  }
9867  }
9868 
9869  ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9870  if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9871  // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9872  // are implicitly inline.
9873  NewFD->setImplicitlyInline();
9874 
9875  // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9876  // be either constructors or to return a literal type. Therefore,
9877  // destructors cannot be declared constexpr.
9878  if (isa<CXXDestructorDecl>(NewFD) &&
9879  (!getLangOpts().CPlusPlus20 ||
9880  ConstexprKind == ConstexprSpecKind::Consteval)) {
9881  Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9882  << static_cast<int>(ConstexprKind);
9883  NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9886  }
9887  // C++20 [dcl.constexpr]p2: An allocation function, or a
9888  // deallocation function shall not be declared with the consteval
9889  // specifier.
9890  if (ConstexprKind == ConstexprSpecKind::Consteval &&
9891  (NewFD->getOverloadedOperator() == OO_New ||
9892  NewFD->getOverloadedOperator() == OO_Array_New ||
9893  NewFD->getOverloadedOperator() == OO_Delete ||
9894  NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9896  diag::err_invalid_consteval_decl_kind)
9897  << NewFD;
9899  }
9900  }
9901 
9902  // If __module_private__ was specified, mark the function accordingly.
9904  if (isFunctionTemplateSpecialization) {
9905  SourceLocation ModulePrivateLoc
9907  Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9908  << 0
9909  << FixItHint::CreateRemoval(ModulePrivateLoc);
9910  } else {
9911  NewFD->setModulePrivate();
9912  if (FunctionTemplate)
9913  FunctionTemplate->setModulePrivate();
9914  }
9915  }
9916 
9917  if (isFriend) {
9918  if (FunctionTemplate) {
9919  FunctionTemplate->setObjectOfFriendDecl();
9920  FunctionTemplate->setAccess(AS_public);
9921  }
9922  NewFD->setObjectOfFriendDecl();
9923  NewFD->setAccess(AS_public);
9924  }
9925 
9926  // If a function is defined as defaulted or deleted, mark it as such now.
9927  // We'll do the relevant checks on defaulted / deleted functions later.
9928  switch (D.getFunctionDefinitionKind()) {
9931  break;
9932 
9934  NewFD->setDefaulted();
9935  break;
9936 
9938  NewFD->setDeletedAsWritten();
9939  break;
9940  }
9941 
9942  if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9943  D.isFunctionDefinition() && !isInline) {
9944  // Pre C++20 [class.mfct]p2:
9945  // A member function may be defined (8.4) in its class definition, in
9946  // which case it is an inline member function (7.1.2)
9947  // Post C++20 [class.mfct]p1:
9948  // If a member function is attached to the global module and is defined
9949  // in its class definition, it is inline.
9950  NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9951  }
9952 
9953  if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9954  !CurContext->isRecord()) {
9955  // C++ [class.static]p1:
9956  // A data or function member of a class may be declared static
9957  // in a class definition, in which case it is a static member of
9958  // the class.
9959 
9960  // Complain about the 'static' specifier if it's on an out-of-line
9961  // member function definition.
9962 
9963  // MSVC permits the use of a 'static' storage specifier on an out-of-line
9964  // member function template declaration and class member template
9965  // declaration (MSVC versions before 2015), warn about this.
9967  ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9968  cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9969  (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9970  ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9972  }
9973 
9974  // C++11 [except.spec]p15:
9975  // A deallocation function with no exception-specification is treated
9976  // as if it were specified with noexcept(true).
9977  const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9978  if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9979  Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9980  getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9981  NewFD->setType(Context.getFunctionType(
9982  FPT->getReturnType(), FPT->getParamTypes(),
9984 
9985  // C++20 [dcl.inline]/7
9986  // If an inline function or variable that is attached to a named module
9987  // is declared in a definition domain, it shall be defined in that
9988  // domain.
9989  // So, if the current declaration does not have a definition, we must
9990  // check at the end of the TU (or when the PMF starts) to see that we
9991  // have a definition at that point.
9992  if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
9993  NewFD->hasOwningModule() &&
9994  NewFD->getOwningModule()->isModulePurview()) {
9995  PendingInlineFuncDecls.insert(NewFD);
9996  }
9997  }
9998 
9999  // Filter out previous declarations that don't match the scope.
10000  FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
10001  D.getCXXScopeSpec().isNotEmpty() ||
10002  isMemberSpecialization ||
10003  isFunctionTemplateSpecialization);
10004 
10005  // Handle GNU asm-label extension (encoded as an attribute).
10006  if (Expr *E = (Expr*) D.getAsmLabel()) {
10007  // The parser guarantees this is a string.
10008  StringLiteral *SE = cast<StringLiteral>(E);
10009  NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10010  /*IsLiteralLabel=*/true,
10011  SE->getStrTokenLoc(0)));
10012  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10013  llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10014  ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
10015  if (I != ExtnameUndeclaredIdentifiers.end()) {
10016  if (isDeclExternC(NewFD)) {
10017  NewFD->addAttr(I->second);
10018  ExtnameUndeclaredIdentifiers.erase(I);
10019  } else
10020  Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10021  << /*Variable*/0 << NewFD;
10022  }
10023  }
10024 
10025  // Copy the parameter declarations from the declarator D to the function
10026  // declaration NewFD, if they are available. First scavenge them into Params.
10028  unsigned FTIIdx;
10029  if (D.isFunctionDeclarator(FTIIdx)) {
10031 
10032  // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10033  // function that takes no arguments, not a function that takes a
10034  // single void argument.
10035  // We let through "const void" here because Sema::GetTypeForDeclarator
10036  // already checks for that case.
10037  if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10038  for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10039  ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10040  assert(Param->getDeclContext() != NewFD && "Was set before ?");
10041  Param->setDeclContext(NewFD);
10042  Params.push_back(Param);
10043 
10044  if (Param->isInvalidDecl())
10045  NewFD->setInvalidDecl();
10046  }
10047  }
10048 
10049  if (!getLangOpts().CPlusPlus) {
10050  // In C, find all the tag declarations from the prototype and move them
10051  // into the function DeclContext. Remove them from the surrounding tag
10052  // injection context of the function, which is typically but not always
10053  // the TU.
10054  DeclContext *PrototypeTagContext =
10056  for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10057  auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10058 
10059  // We don't want to reparent enumerators. Look at their parent enum
10060  // instead.
10061  if (!TD) {
10062  if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10063  TD = cast<EnumDecl>(ECD->getDeclContext());
10064  }
10065  if (!TD)
10066  continue;
10067  DeclContext *TagDC = TD->getLexicalDeclContext();
10068  if (!TagDC->containsDecl(TD))
10069  continue;
10070  TagDC->removeDecl(TD);
10071  TD->setDeclContext(NewFD);
10072  NewFD->addDecl(TD);
10073 
10074  // Preserve the lexical DeclContext if it is not the surrounding tag
10075  // injection context of the FD. In this example, the semantic context of
10076  // E will be f and the lexical context will be S, while both the
10077  // semantic and lexical contexts of S will be f:
10078  // void f(struct S { enum E { a } f; } s);
10079  if (TagDC != PrototypeTagContext)
10080  TD->setLexicalDeclContext(TagDC);
10081  }
10082  }
10083  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10084  // When we're declaring a function with a typedef, typeof, etc as in the
10085  // following example, we'll need to synthesize (unnamed)
10086  // parameters for use in the declaration.
10087  //
10088  // @code
10089  // typedef void fn(int);
10090  // fn f;
10091  // @endcode
10092 
10093  // Synthesize a parameter for each argument type.
10094  for (const auto &AI : FT->param_types()) {
10095  ParmVarDecl *Param =
10096  BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10097  Param->setScopeInfo(0, Params.size());
10098  Params.push_back(Param);
10099  }
10100  } else {
10101  assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10102  "Should not need args for typedef of non-prototype fn");
10103  }
10104 
10105  // Finally, we know we have the right number of parameters, install them.
10106  NewFD->setParams(Params);
10107 
10108  if (D.getDeclSpec().isNoreturnSpecified())
10109  NewFD->addAttr(C11NoReturnAttr::Create(Context,
10112 
10113  // Functions returning a variably modified type violate C99 6.7.5.2p2
10114  // because all functions have linkage.
10115  if (!NewFD->isInvalidDecl() &&
10116  NewFD->getReturnType()->isVariablyModifiedType()) {
10117  Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10118  NewFD->setInvalidDecl();
10119  }
10120 
10121  // Apply an implicit SectionAttr if '#pragma clang section text' is active
10122  if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10123  !NewFD->hasAttr<SectionAttr>())
10124  NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10125  Context, PragmaClangTextSection.SectionName,
10126  PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
10127 
10128  // Apply an implicit SectionAttr if #pragma code_seg is active.
10129  if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10130  !NewFD->hasAttr<SectionAttr>()) {
10131  NewFD->addAttr(SectionAttr::CreateImplicit(
10132  Context, CodeSegStack.CurrentValue->getString(),
10133  CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10134  SectionAttr::Declspec_allocate));
10135  if (UnifySection(CodeSegStack.CurrentValue->getString(),
10138  NewFD))
10139  NewFD->dropAttr<SectionAttr>();
10140  }
10141 
10142  // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10143  // active.
10144  if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10145  !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10146  NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10147  Context, PragmaClangTextSection.PragmaLocation,
10149 
10150  // Apply an implicit CodeSegAttr from class declspec or
10151  // apply an implicit SectionAttr from #pragma code_seg if active.
10152  if (!NewFD->hasAttr<CodeSegAttr>()) {
10153  if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
10154  D.isFunctionDefinition())) {
10155  NewFD->addAttr(SAttr);
10156  }
10157  }
10158 
10159  // Handle attributes.
10160  ProcessDeclAttributes(S, NewFD, D);
10161  const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10162  if (NewTVA && !NewTVA->isDefaultVersion() &&
10163  !Context.getTargetInfo().hasFeature("fmv")) {
10164  // Don't add to scope fmv functions declarations if fmv disabled
10165  AddToScope = false;
10166  return NewFD;
10167  }
10168 
10169  if (getLangOpts().OpenCL) {
10170  // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10171  // type declaration will generate a compilation error.
10172  LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10173  if (AddressSpace != LangAS::Default) {
10174  Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10175  NewFD->setInvalidDecl();
10176  }
10177  }
10178 
10179  if (getLangOpts().HLSL) {
10180  auto &TargetInfo = getASTContext().getTargetInfo();
10181  // Skip operator overload which not identifier.
10182  // Also make sure NewFD is in translation-unit scope.
10183  if (!NewFD->isInvalidDecl() && Name.isIdentifier() &&
10184  NewFD->getName() == TargetInfo.getTargetOpts().HLSLEntry &&
10185  S->getDepth() == 0) {
10186  CheckHLSLEntryPoint(NewFD);
10187  if (!NewFD->isInvalidDecl()) {
10188  auto Env = TargetInfo.getTriple().getEnvironment();
10189  AttributeCommonInfo AL(NewFD->getBeginLoc());
10190  HLSLShaderAttr::ShaderType ShaderType =
10191  static_cast<HLSLShaderAttr::ShaderType>(
10193  // To share code with HLSLShaderAttr, add HLSLShaderAttr to entry
10194  // function.
10195  if (HLSLShaderAttr *Attr = mergeHLSLShaderAttr(NewFD, AL, ShaderType))
10196  NewFD->addAttr(Attr);
10197  }
10198  }
10199  // HLSL does not support specifying an address space on a function return
10200  // type.
10201  LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10202  if (AddressSpace != LangAS::Default) {
10203  Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10204  NewFD->setInvalidDecl();
10205  }
10206  }
10207 
10208  if (!getLangOpts().CPlusPlus) {
10209  // Perform semantic checking on the function declaration.
10210  if (!NewFD->isInvalidDecl() && NewFD->isMain())
10211  CheckMain(NewFD, D.getDeclSpec());
10212 
10213  if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10214  CheckMSVCRTEntryPoint(NewFD);
10215 
10216  if (!NewFD->isInvalidDecl())
10217  D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10218  isMemberSpecialization,
10219  D.isFunctionDefinition()));
10220  else if (!Previous.empty())
10221  // Recover gracefully from an invalid redeclaration.
10222  D.setRedeclaration(true);
10223  assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10224  Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10225  "previous declaration set still overloaded");
10226 
10227  // Diagnose no-prototype function declarations with calling conventions that
10228  // don't support variadic calls. Only do this in C and do it after merging
10229  // possibly prototyped redeclarations.
10230  const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10231  if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10232  CallingConv CC = FT->getExtInfo().getCC();
10233  if (!supportsVariadicCall(CC)) {
10234  // Windows system headers sometimes accidentally use stdcall without
10235  // (void) parameters, so we relax this to a warning.
10236  int DiagID =
10237  CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10238  Diag(NewFD->getLocation(), DiagID)
10240  }
10241  }
10242 
10245  checkNonTrivialCUnion(NewFD->getReturnType(),
10247  NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
10248  } else {
10249  // C++11 [replacement.functions]p3:
10250  // The program's definitions shall not be specified as inline.
10251  //
10252  // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10253  //
10254  // Suppress the diagnostic if the function is __attribute__((used)), since
10255  // that forces an external definition to be emitted.
10256  if (D.getDeclSpec().isInlineSpecified() &&
10258  !NewFD->hasAttr<UsedAttr>())
10260  diag::ext_operator_new_delete_declared_inline)
10261  << NewFD->getDeclName();
10262 
10263  // If the declarator is a template-id, translate the parser's template
10264  // argument list into our AST format.
10266  TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
10267  TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10268  TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10269  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10270  TemplateId->NumArgs);
10271  translateTemplateArguments(TemplateArgsPtr,
10272  TemplateArgs);
10273 
10274  HasExplicitTemplateArgs = true;
10275 
10276  if (NewFD->isInvalidDecl()) {
10277  HasExplicitTemplateArgs = false;
10278  } else if (FunctionTemplate) {
10279  // Function template with explicit template arguments.
10280  Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10281  << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10282 
10283  HasExplicitTemplateArgs = false;
10284  } else {
10285  assert((isFunctionTemplateSpecialization ||
10286  D.getDeclSpec().isFriendSpecified()) &&
10287  "should have a 'template<>' for this decl");
10288  // "friend void foo<>(int);" is an implicit specialization decl.
10289  isFunctionTemplateSpecialization = true;
10290  }
10291  } else if (isFriend && isFunctionTemplateSpecialization) {
10292  // This combination is only possible in a recovery case; the user
10293  // wrote something like:
10294  // template <> friend void foo(int);
10295  // which we're recovering from as if the user had written:
10296  // friend void foo<>(int);
10297  // Go ahead and fake up a template id.
10298  HasExplicitTemplateArgs = true;
10299  TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
10300  TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
10301  }
10302 
10303  // We do not add HD attributes to specializations here because
10304  // they may have different constexpr-ness compared to their
10305  // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
10306  // may end up with different effective targets. Instead, a
10307  // specialization inherits its target attributes from its template
10308  // in the CheckFunctionTemplateSpecialization() call below.
10309  if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10310  maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
10311 
10312  // If it's a friend (and only if it's a friend), it's possible
10313  // that either the specialized function type or the specialized
10314  // template is dependent, and therefore matching will fail. In
10315  // this case, don't check the specialization yet.
10316  if (isFunctionTemplateSpecialization && isFriend &&
10317  (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
10319  TemplateArgs.arguments()))) {
10320  assert(HasExplicitTemplateArgs &&
10321  "friend function specialization without template args");
10322  if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
10323  Previous))
10324  NewFD->setInvalidDecl();
10325  } else if (isFunctionTemplateSpecialization) {
10326  if (CurContext->isDependentContext() && CurContext->isRecord()
10327  && !isFriend) {
10328  isDependentClassScopeExplicitSpecialization = true;
10329  } else if (!NewFD->isInvalidDecl() &&
10330  CheckFunctionTemplateSpecialization(
10331  NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
10332  Previous))
10333  NewFD->setInvalidDecl();
10334 
10335  // C++ [dcl.stc]p1:
10336  // A storage-class-specifier shall not be specified in an explicit
10337  // specialization (14.7.3)
10340  if (Info && SC != SC_None) {
10341  if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10342  Diag(NewFD->getLocation(),
10343  diag::err_explicit_specialization_inconsistent_storage_class)
10344  << SC
10347 
10348  else
10349  Diag(NewFD->getLocation(),
10350  diag::ext_explicit_specialization_storage_class)
10353  }
10354  } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10355  if (CheckMemberSpecialization(NewFD, Previous))
10356  NewFD->setInvalidDecl();
10357  }
10358 
10359  // Perform semantic checking on the function declaration.
10360  if (!isDependentClassScopeExplicitSpecialization) {
10361  if (!NewFD->isInvalidDecl() && NewFD->isMain())
10362  CheckMain(NewFD, D.getDeclSpec());
10363 
10364  if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10365  CheckMSVCRTEntryPoint(NewFD);
10366 
10367  if (!NewFD->isInvalidDecl())
10368  D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10369  isMemberSpecialization,
10370  D.isFunctionDefinition()));
10371  else if (!Previous.empty())
10372  // Recover gracefully from an invalid redeclaration.
10373  D.setRedeclaration(true);
10374  }
10375 
10376  assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10377  !D.isRedeclaration() ||
10378  Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10379  "previous declaration set still overloaded");
10380 
10381  NamedDecl *PrincipalDecl = (FunctionTemplate
10382  ? cast<NamedDecl>(FunctionTemplate)
10383  : NewFD);
10384 
10385  if (isFriend && NewFD->getPreviousDecl()) {
10386  AccessSpecifier Access = AS_public;
10387  if (!NewFD->isInvalidDecl())
10388  Access = NewFD->getPreviousDecl()->getAccess();
10389 
10390  NewFD->setAccess(Access);
10391  if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10392  }
10393 
10394  if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10396  PrincipalDecl->setNonMemberOperator();
10397 
10398  // If we have a function template, check the template parameter
10399  // list. This will check and merge default template arguments.
10400  if (FunctionTemplate) {
10401  FunctionTemplateDecl *PrevTemplate =
10402  FunctionTemplate->getPreviousDecl();
10403  CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10404  PrevTemplate ? PrevTemplate->getTemplateParameters()
10405  : nullptr,
10407  ? (D.isFunctionDefinition()
10408  ? TPC_FriendFunctionTemplateDefinition
10409  : TPC_FriendFunctionTemplate)
10410  : (D.getCXXScopeSpec().isSet() &&
10411  DC && DC->isRecord() &&
10412  DC->isDependentContext())
10413  ? TPC_ClassTemplateMember
10414  : TPC_FunctionTemplate);
10415  }
10416 
10417  if (NewFD->isInvalidDecl()) {
10418  // Ignore all the rest of this.
10419  } else if (!D.isRedeclaration()) {
10420  struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10421  AddToScope };
10422  // Fake up an access specifier if it's supposed to be a class member.
10423  if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10424  NewFD->setAccess(AS_public);
10425 
10426  // Qualified decls generally require a previous declaration.
10427  if (D.getCXXScopeSpec().isSet()) {
10428  // ...with the major exception of templated-scope or
10429  // dependent-scope friend declarations.
10430 
10431  // TODO: we currently also suppress this check in dependent
10432  // contexts because (1) the parameter depth will be off when
10433  // matching friend templates and (2) we might actually be
10434  // selecting a friend based on a dependent factor. But there
10435  // are situations where these conditions don't apply and we
10436  // can actually do this check immediately.
10437  //
10438  // Unless the scope is dependent, it's always an error if qualified
10439  // redeclaration lookup found nothing at all. Diagnose that now;
10440  // nothing will diagnose that error later.
10441  if (isFriend &&
10443  (!Previous.empty() && CurContext->isDependentContext()))) {
10444  // ignore these
10445  } else if (NewFD->isCPUDispatchMultiVersion() ||
10446  NewFD->isCPUSpecificMultiVersion()) {
10447  // ignore this, we allow the redeclaration behavior here to create new
10448  // versions of the function.
10449  } else {
10450  // The user tried to provide an out-of-line definition for a
10451  // function that is a member of a class or namespace, but there
10452  // was no such member function declared (C++ [class.mfct]p2,
10453  // C++ [namespace.memdef]p2). For example:
10454  //
10455  // class X {
10456  // void f() const;
10457  // };
10458  //
10459  // void X::f() { } // ill-formed
10460  //
10461  // Complain about this problem, and attempt to suggest close
10462  // matches (e.g., those that differ only in cv-qualifiers and
10463  // whether the parameter types are references).
10464 
10466  *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10467  AddToScope = ExtraArgs.AddToScope;
10468  return Result;
10469  }
10470  }
10471 
10472  // Unqualified local friend declarations are required to resolve
10473  // to something.
10474  } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10476  *this, Previous, NewFD, ExtraArgs, true, S)) {
10477  AddToScope = ExtraArgs.AddToScope;
10478  return Result;
10479  }
10480  }
10481  } else if (!D.isFunctionDefinition() &&
10482  isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10483  !isFriend && !isFunctionTemplateSpecialization &&
10484  !isMemberSpecialization) {
10485  // An out-of-line member function declaration must also be a
10486  // definition (C++ [class.mfct]p2).
10487  // Note that this is not the case for explicit specializations of
10488  // function templates or member functions of class templates, per
10489  // C++ [temp.expl.spec]p2. We also allow these declarations as an
10490  // extension for compatibility with old SWIG code which likes to
10491  // generate them.
10492  Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10493  << D.getCXXScopeSpec().getRange();
10494  }
10495  }
10496 
10497  // If this is the first declaration of a library builtin function, add
10498  // attributes as appropriate.
10499  if (!D.isRedeclaration()) {
10500  if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10501  if (unsigned BuiltinID = II->getBuiltinID()) {
10502  bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10503  if (!InStdNamespace &&
10505  if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10506  // Validate the type matches unless this builtin is specified as
10507  // matching regardless of its declared type.
10508  if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10509  NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10510  } else {
10512  LookupNecessaryTypesForBuiltin(S, BuiltinID);
10513  QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10514 
10515  if (!Error && !BuiltinType.isNull() &&
10517  NewFD->getType(), BuiltinType))
10518  NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10519  }
10520  }
10521  } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10522  isStdBuiltin(Context, NewFD, BuiltinID)) {
10523  NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10524  }
10525  }
10526  }
10527  }
10528 
10529  ProcessPragmaWeak(S, NewFD);
10530  checkAttributesAfterMerging(*this, *NewFD);
10531 
10532  AddKnownFunctionAttributes(NewFD);
10533 
10534  if (NewFD->hasAttr<OverloadableAttr>() &&
10535  !NewFD->getType()->getAs<FunctionProtoType>()) {
10536  Diag(NewFD->getLocation(),
10537  diag::err_attribute_overloadable_no_prototype)
10538  << NewFD;
10539  NewFD->dropAttr<OverloadableAttr>();
10540  }
10541 
10542  // If there's a #pragma GCC visibility in scope, and this isn't a class
10543  // member, set the visibility of this function.
10544  if (!DC->isRecord() && NewFD->isExternallyVisible())
10545  AddPushedVisibilityAttribute(NewFD);
10546 
10547  // If there's a #pragma clang arc_cf_code_audited in scope, consider
10548  // marking the function.
10549  AddCFAuditedAttribute(NewFD);
10550 
10551  // If this is a function definition, check if we have to apply any
10552  // attributes (i.e. optnone and no_builtin) due to a pragma.
10553  if (D.isFunctionDefinition()) {
10554  AddRangeBasedOptnone(NewFD);
10555  AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10556  AddSectionMSAllocText(NewFD);
10557  ModifyFnAttributesMSPragmaOptimize(NewFD);
10558  }
10559 
10560  // If this is the first declaration of an extern C variable, update
10561  // the map of such variables.
10562  if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10563  isIncompleteDeclExternC(*this, NewFD))
10564  RegisterLocallyScopedExternCDecl(NewFD, S);
10565 
10566  // Set this FunctionDecl's range up to the right paren.
10567  NewFD->setRangeEnd(D.getSourceRange().getEnd());
10568 
10569  if (D.isRedeclaration() && !Previous.empty()) {
10570  NamedDecl *Prev = Previous.getRepresentativeDecl();
10571  checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10572  isMemberSpecialization ||
10573  isFunctionTemplateSpecialization,
10574  D.isFunctionDefinition());
10575  }
10576 
10577  if (getLangOpts().CUDA) {
10578  IdentifierInfo *II = NewFD->getIdentifier();
10579  if (II && II->isStr(getCudaConfigureFuncName()) &&
10580  !NewFD->isInvalidDecl() &&
10582  if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10583  Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10584  << getCudaConfigureFuncName();
10585  Context.setcudaConfigureCallDecl(NewFD);
10586  }
10587 
10588  // Variadic functions, other than a *declaration* of printf, are not allowed
10589  // in device-side CUDA code, unless someone passed
10590  // -fcuda-allow-variadic-functions.
10591  if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10592  (NewFD->hasAttr<CUDADeviceAttr>() ||
10593  NewFD->hasAttr<CUDAGlobalAttr>()) &&
10594  !(II && II->isStr("printf") && NewFD->isExternC() &&
10595  !D.isFunctionDefinition())) {
10596  Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10597  }
10598  }
10599 
10600  MarkUnusedFileScopedDecl(NewFD);
10601 
10602 
10603 
10604  if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10605  // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10606  if (SC == SC_Static) {
10607  Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10608  D.setInvalidType();
10609  }
10610 
10611  // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10612  if (!NewFD->getReturnType()->isVoidType()) {
10613  SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10614  Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10615  << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10616  : FixItHint());
10617  D.setInvalidType();
10618  }
10619 
10621  for (auto *Param : NewFD->parameters())
10622  checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10623 
10624  if (getLangOpts().OpenCLCPlusPlus) {
10625  if (DC->isRecord()) {
10626  Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10627  D.setInvalidType();
10628  }
10629  if (FunctionTemplate) {
10630  Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10631  D.setInvalidType();
10632  }
10633  }
10634  }
10635 
10636  if (getLangOpts().CPlusPlus) {
10637  // Precalculate whether this is a friend function template with a constraint
10638  // that depends on an enclosing template, per [temp.friend]p9.
10639  if (isFriend && FunctionTemplate &&
10640  FriendConstraintsDependOnEnclosingTemplate(NewFD))
10642 
10643  if (FunctionTemplate) {
10644  if (NewFD->isInvalidDecl())
10645  FunctionTemplate->setInvalidDecl();
10646  return FunctionTemplate;
10647  }
10648 
10649  if (isMemberSpecialization && !NewFD->isInvalidDecl())
10650  CompleteMemberSpecialization(NewFD, Previous);
10651  }
10652 
10653  for (const ParmVarDecl *Param : NewFD->parameters()) {
10654  QualType PT = Param->getType();
10655 
10656  // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10657  // types.
10658  if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10659  if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10660  QualType ElemTy = PipeTy->getElementType();
10661  if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10662  Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10663  D.setInvalidType();
10664  }
10665  }
10666  }
10667  }
10668 
10669  // Here we have an function template explicit specialization at class scope.
10670  // The actual specialization will be postponed to template instatiation
10671  // time via the ClassScopeFunctionSpecializationDecl node.
10672  if (isDependentClassScopeExplicitSpecialization) {
10675  Context, CurContext, NewFD->getLocation(),
10676  cast<CXXMethodDecl>(NewFD),
10677  HasExplicitTemplateArgs, TemplateArgs);
10678  CurContext->addDecl(NewSpec);
10679  AddToScope = false;
10680  }
10681 
10682  // Diagnose availability attributes. Availability cannot be used on functions
10683  // that are run during load/unload.
10684  if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10685  if (NewFD->hasAttr<ConstructorAttr>()) {
10686  Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10687  << 1;
10688  NewFD->dropAttr<AvailabilityAttr>();
10689  }
10690  if (NewFD->hasAttr<DestructorAttr>()) {
10691  Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10692  << 2;
10693  NewFD->dropAttr<AvailabilityAttr>();
10694  }
10695  }
10696 
10697  // Diagnose no_builtin attribute on function declaration that are not a
10698  // definition.
10699  // FIXME: We should really be doing this in
10700  // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10701  // the FunctionDecl and at this point of the code
10702  // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10703  // because Sema::ActOnStartOfFunctionDef has not been called yet.
10704  if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10705  switch (D.getFunctionDefinitionKind()) {
10708  Diag(NBA->getLocation(),
10709  diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10710  << NBA->getSpelling();
10711  break;
10713  Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10714  << NBA->getSpelling();
10715  break;
10717  break;
10718  }
10719 
10720  return NewFD;
10721 }
10722 
10723 /// Return a CodeSegAttr from a containing class. The Microsoft docs say
10724 /// when __declspec(code_seg) "is applied to a class, all member functions of
10725 /// the class and nested classes -- this includes compiler-generated special
10726 /// member functions -- are put in the specified segment."
10727 /// The actual behavior is a little more complicated. The Microsoft compiler
10728 /// won't check outer classes if there is an active value from #pragma code_seg.
10729 /// The CodeSeg is always applied from the direct parent but only from outer
10730 /// classes when the #pragma code_seg stack is empty. See:
10731 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10732 /// available since MS has removed the page.
10734  const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10735  if (!Method)
10736  return nullptr;
10737  const CXXRecordDecl *Parent = Method->getParent();
10738  if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10739  Attr *NewAttr = SAttr->clone(S.getASTContext());
10740  NewAttr->setImplicit(true);
10741  return NewAttr;
10742  }
10743 
10744  // The Microsoft compiler won't check outer classes for the CodeSeg
10745  // when the #pragma code_seg stack is active.
10746  if (S.CodeSegStack.CurrentValue)
10747  return nullptr;
10748 
10749  while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10750  if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10751  Attr *NewAttr = SAttr->clone(S.getASTContext());
10752  NewAttr->setImplicit(true);
10753  return NewAttr;
10754  }
10755  }
10756  return nullptr;
10757 }
10758 
10759 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10760 /// containing class. Otherwise it will return implicit SectionAttr if the
10761 /// function is a definition and there is an active value on CodeSegStack
10762 /// (from the current #pragma code-seg value).
10763 ///
10764 /// \param FD Function being declared.
10765 /// \param IsDefinition Whether it is a definition or just a declaration.
10766 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10767 /// nullptr if no attribute should be added.
10769  bool IsDefinition) {
10770  if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10771  return A;
10772  if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10773  CodeSegStack.CurrentValue)
10774  return SectionAttr::CreateImplicit(
10775  getASTContext(), CodeSegStack.CurrentValue->getString(),
10776  CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10777  SectionAttr::Declspec_allocate);
10778  return nullptr;
10779 }
10780 
10781 /// Determines if we can perform a correct type check for \p D as a
10782 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10783 /// best-effort check.
10784 ///
10785 /// \param NewD The new declaration.
10786 /// \param OldD The old declaration.
10787 /// \param NewT The portion of the type of the new declaration to check.
10788 /// \param OldT The portion of the type of the old declaration to check.
10790  QualType NewT, QualType OldT) {
10791  if (!NewD->getLexicalDeclContext()->isDependentContext())
10792  return true;
10793 
10794  // For dependently-typed local extern declarations and friends, we can't
10795  // perform a correct type check in general until instantiation:
10796  //
10797  // int f();
10798  // template<typename T> void g() { T f(); }
10799  //
10800  // (valid if g() is only instantiated with T = int).
10801  if (NewT->isDependentType() &&
10802  (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10803  return false;
10804 
10805  // Similarly, if the previous declaration was a dependent local extern
10806  // declaration, we don't really know its type yet.
10807  if (OldT->isDependentType() && OldD->isLocalExternDecl())
10808  return false;
10809 
10810  return true;
10811 }
10812 
10813 /// Checks if the new declaration declared in dependent context must be
10814 /// put in the same redeclaration chain as the specified declaration.
10815 ///
10816 /// \param D Declaration that is checked.
10817 /// \param PrevDecl Previous declaration found with proper lookup method for the
10818 /// same declaration name.
10819 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10820 /// belongs to.
10821 ///
10824  return true;
10825 
10826  // Don't chain dependent friend function definitions until instantiation, to
10827  // permit cases like
10828  //
10829  // void func();
10830  // template<typename T> class C1 { friend void func() {} };
10831  // template<typename T> class C2 { friend void func() {} };
10832  //
10833  // ... which is valid if only one of C1 and C2 is ever instantiated.
10834  //
10835  // FIXME: This need only apply to function definitions. For now, we proxy
10836  // this by checking for a file-scope function. We do not want this to apply
10837  // to friend declarations nominating member functions, because that gets in
10838  // the way of access checks.
10839  if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10840  return false;
10841 
10842  auto *VD = dyn_cast<ValueDecl>(D);
10843  auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10844  return !VD || !PrevVD ||
10845  canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10846  PrevVD->getType());
10847 }
10848 
10849 /// Check the target or target_version attribute of the function for
10850 /// MultiVersion validity.
10851 ///
10852 /// Returns true if there was an error, false otherwise.
10853 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10854  const auto *TA = FD->getAttr<TargetAttr>();
10855  const auto *TVA = FD->getAttr<TargetVersionAttr>();
10856  assert(
10857  (TA || TVA) &&
10858  "MultiVersion candidate requires a target or target_version attribute");
10860  enum ErrType { Feature = 0, Architecture = 1 };
10861 
10862  if (TA) {
10863  ParsedTargetAttr ParseInfo =
10864  S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
10865  if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
10866  S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10867  << Architecture << ParseInfo.CPU;
10868  return true;
10869  }
10870  for (const auto &Feat : ParseInfo.Features) {
10871  auto BareFeat = StringRef{Feat}.substr(1);
10872  if (Feat[0] == '-') {
10873  S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10874  << Feature << ("no-" + BareFeat).str();
10875  return true;
10876  }
10877 
10878  if (!TargetInfo.validateCpuSupports(BareFeat) ||
10879  !TargetInfo.isValidFeatureName(BareFeat)) {
10880  S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10881  << Feature << BareFeat;
10882  return true;
10883  }
10884  }
10885  }
10886 
10887  if (TVA) {
10889  TVA->getFeatures(Feats);
10890  for (const auto &Feat : Feats) {
10891  if (!TargetInfo.validateCpuSupports(Feat)) {
10892  S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10893  << Feature << Feat;
10894  return true;
10895  }
10896  }
10897  }
10898  return false;
10899 }
10900 
10901 // Provide a white-list of attributes that are allowed to be combined with
10902 // multiversion functions.
10904  MultiVersionKind MVKind) {
10905  // Note: this list/diagnosis must match the list in
10906  // checkMultiversionAttributesAllSame.
10907  switch (Kind) {
10908  default:
10909  return false;
10910  case attr::Used:
10911  return MVKind == MultiVersionKind::Target;
10912  case attr::NonNull:
10913  case attr::NoThrow:
10914  return true;
10915  }
10916 }
10917 
10919  const FunctionDecl *FD,
10920  const FunctionDecl *CausedFD,
10921  MultiVersionKind MVKind) {
10922  const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
10923  S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10924  << static_cast<unsigned>(MVKind) << A;
10925  if (CausedFD)
10926  S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10927  return true;
10928  };
10929 
10930  for (const Attr *A : FD->attrs()) {
10931  switch (A->getKind()) {
10932  case attr::CPUDispatch:
10933  case attr::CPUSpecific:
10934  if (MVKind != MultiVersionKind::CPUDispatch &&
10936  return Diagnose(S, A);
10937  break;
10938  case attr::Target:
10939  if (MVKind != MultiVersionKind::Target)
10940  return Diagnose(S, A);
10941  break;
10942  case attr::TargetVersion:
10943  if (MVKind != MultiVersionKind::TargetVersion)
10944  return Diagnose(S, A);
10945  break;
10946  case attr::TargetClones:
10947  if (MVKind != MultiVersionKind::TargetClones)
10948  return Diagnose(S, A);
10949  break;
10950  default:
10951  if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
10952  return Diagnose(S, A);
10953  break;
10954  }
10955  }
10956  return false;
10957 }
10958 
10960  const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10961  const PartialDiagnostic &NoProtoDiagID,
10962  const PartialDiagnosticAt &NoteCausedDiagIDAt,
10963  const PartialDiagnosticAt &NoSupportDiagIDAt,
10964  const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10965  bool ConstexprSupported, bool CLinkageMayDiffer) {
10966  enum DoesntSupport {
10967  FuncTemplates = 0,
10968  VirtFuncs = 1,
10969  DeducedReturn = 2,
10970  Constructors = 3,
10971  Destructors = 4,
10972  DeletedFuncs = 5,
10973  DefaultedFuncs = 6,
10974  ConstexprFuncs = 7,
10975  ConstevalFuncs = 8,
10976  Lambda = 9,
10977  };
10978  enum Different {
10979  CallingConv = 0,
10980  ReturnType = 1,
10981  ConstexprSpec = 2,
10982  InlineSpec = 3,
10983  Linkage = 4,
10984  LanguageLinkage = 5,
10985  };
10986 
10987  if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10988  !OldFD->getType()->getAs<FunctionProtoType>()) {
10989  Diag(OldFD->getLocation(), NoProtoDiagID);
10990  Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10991  return true;
10992  }
10993 
10994  if (NoProtoDiagID.getDiagID() != 0 &&
10995  !NewFD->getType()->getAs<FunctionProtoType>())
10996  return Diag(NewFD->getLocation(), NoProtoDiagID);
10997 
10998  if (!TemplatesSupported &&
11000  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11001  << FuncTemplates;
11002 
11003  if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11004  if (NewCXXFD->isVirtual())
11005  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11006  << VirtFuncs;
11007 
11008  if (isa<CXXConstructorDecl>(NewCXXFD))
11009  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11010  << Constructors;
11011 
11012  if (isa<CXXDestructorDecl>(NewCXXFD))
11013  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11014  << Destructors;
11015  }
11016 
11017  if (NewFD->isDeleted())
11018  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11019  << DeletedFuncs;
11020 
11021  if (NewFD->isDefaulted())
11022  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11023  << DefaultedFuncs;
11024 
11025  if (!ConstexprSupported && NewFD->isConstexpr())
11026  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11027  << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11028 
11029  QualType NewQType = Context.getCanonicalType(NewFD->getType());
11030  const auto *NewType = cast<FunctionType>(NewQType);
11031  QualType NewReturnType = NewType->getReturnType();
11032 
11033  if (NewReturnType->isUndeducedType())
11034  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11035  << DeducedReturn;
11036 
11037  // Ensure the return type is identical.
11038  if (OldFD) {
11039  QualType OldQType = Context.getCanonicalType(OldFD->getType());
11040  const auto *OldType = cast<FunctionType>(OldQType);
11041  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11042  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11043 
11044  if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
11045  return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11046 
11047  QualType OldReturnType = OldType->getReturnType();
11048 
11049  if (OldReturnType != NewReturnType)
11050  return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11051 
11052  if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11053  return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11054 
11055  if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11056  return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11057 
11058  if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11059  return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11060 
11061  if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11062  return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11063 
11064  if (CheckEquivalentExceptionSpec(
11065  OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
11066  NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
11067  return true;
11068  }
11069  return false;
11070 }
11071 
11073  const FunctionDecl *NewFD,
11074  bool CausesMV,
11075  MultiVersionKind MVKind) {
11077  S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11078  if (OldFD)
11079  S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11080  return true;
11081  }
11082 
11083  bool IsCPUSpecificCPUDispatchMVKind =
11084  MVKind == MultiVersionKind::CPUDispatch ||
11086 
11087  if (CausesMV && OldFD &&
11088  checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11089  return true;
11090 
11091  if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11092  return true;
11093 
11094  // Only allow transition to MultiVersion if it hasn't been used.
11095  if (OldFD && CausesMV && OldFD->isUsed(false))
11096  return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11097 
11099  OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11101  S.PDiag(diag::note_multiversioning_caused_here)),
11103  S.PDiag(diag::err_multiversion_doesnt_support)
11104  << static_cast<unsigned>(MVKind)),
11106  S.PDiag(diag::err_multiversion_diff)),
11107  /*TemplatesSupported=*/false,
11108  /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11109  /*CLinkageMayDiffer=*/false);
11110 }
11111 
11112 /// Check the validity of a multiversion function declaration that is the
11113 /// first of its kind. Also sets the multiversion'ness' of the function itself.
11114 ///
11115 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11116 ///
11117 /// Returns true if there was an error, false otherwise.
11119  MultiVersionKind MVKind = FD->getMultiVersionKind();
11120  assert(MVKind != MultiVersionKind::None &&
11121  "Function lacks multiversion attribute");
11122  const auto *TA = FD->getAttr<TargetAttr>();
11123  const auto *TVA = FD->getAttr<TargetVersionAttr>();
11124  // Target and target_version only causes MV if it is default, otherwise this
11125  // is a normal function.
11126  if ((TA && !TA->isDefaultVersion()) || (TVA && !TVA->isDefaultVersion()))
11127  return false;
11128 
11129  if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11130  FD->setInvalidDecl();
11131  return true;
11132  }
11133 
11134  if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11135  FD->setInvalidDecl();
11136  return true;
11137  }
11138 
11139  FD->setIsMultiVersion();
11140  return false;
11141 }
11142 
11144  for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11146  return true;
11147  }
11148 
11149  return false;
11150 }
11151 
11153  FunctionDecl *NewFD,
11154  bool &Redeclaration,
11155  NamedDecl *&OldDecl,
11157  const auto *NewTA = NewFD->getAttr<TargetAttr>();
11158  const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11159  const auto *OldTA = OldFD->getAttr<TargetAttr>();
11160  const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11161  // If the old decl is NOT MultiVersioned yet, and we don't cause that
11162  // to change, this is a simple redeclaration.
11163  if ((NewTA && !NewTA->isDefaultVersion() &&
11164  (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) ||
11165  (NewTVA && !NewTVA->isDefaultVersion() &&
11166  (!OldTVA || OldTVA->getName() == NewTVA->getName())))
11167  return false;
11168 
11169  // Otherwise, this decl causes MultiVersioning.
11170  if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11173  NewFD->setInvalidDecl();
11174  return true;
11175  }
11176 
11177  if (CheckMultiVersionValue(S, NewFD)) {
11178  NewFD->setInvalidDecl();
11179  return true;
11180  }
11181 
11182  // If this is 'default', permit the forward declaration.
11183  if (!OldFD->isMultiVersion() &&
11184  ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11185  (NewTVA && NewTVA->isDefaultVersion() && !OldTVA))) {
11186  Redeclaration = true;
11187  OldDecl = OldFD;
11188  OldFD->setIsMultiVersion();
11189  NewFD->setIsMultiVersion();
11190  return false;
11191  }
11192 
11193  if (CheckMultiVersionValue(S, OldFD)) {
11194  S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11195  NewFD->setInvalidDecl();
11196  return true;
11197  }
11198 
11199  if (NewTA) {
11200  ParsedTargetAttr OldParsed =
11202  OldTA->getFeaturesStr());
11203  llvm::sort(OldParsed.Features);
11204  ParsedTargetAttr NewParsed =
11206  NewTA->getFeaturesStr());
11207  // Sort order doesn't matter, it just needs to be consistent.
11208  llvm::sort(NewParsed.Features);
11209  if (OldParsed == NewParsed) {
11210  S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11211  S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11212  NewFD->setInvalidDecl();
11213  return true;
11214  }
11215  }
11216 
11217  if (NewTVA) {
11219  OldTVA->getFeatures(Feats);
11220  llvm::sort(Feats);
11222  NewTVA->getFeatures(NewFeats);
11223  llvm::sort(NewFeats);
11224 
11225  if (Feats == NewFeats) {
11226  S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11227  S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11228  NewFD->setInvalidDecl();
11229  return true;
11230  }
11231  }
11232 
11233  for (const auto *FD : OldFD->redecls()) {
11234  const auto *CurTA = FD->getAttr<TargetAttr>();
11235  const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11236  // We allow forward declarations before ANY multiversioning attributes, but
11237  // nothing after the fact.
11239  ((NewTA && (!CurTA || CurTA->isInherited())) ||
11240  (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11241  S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11242  << (NewTA ? 0 : 2);
11243  S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11244  NewFD->setInvalidDecl();
11245  return true;
11246  }
11247  }
11248 
11249  OldFD->setIsMultiVersion();
11250  NewFD->setIsMultiVersion();
11251  Redeclaration = false;
11252  OldDecl = nullptr;
11253  Previous.clear();
11254  return false;
11255 }
11256 
11258  MultiVersionKind New) {
11259  if (Old == New || Old == MultiVersionKind::None ||
11260  New == MultiVersionKind::None)
11261  return true;
11262 
11263  return (Old == MultiVersionKind::CPUDispatch &&
11267 }
11268 
11269 /// Check the validity of a new function declaration being added to an existing
11270 /// multiversioned declaration collection.
11272  Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11273  MultiVersionKind NewMVKind, const CPUDispatchAttr *NewCPUDisp,
11274  const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones,
11275  bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
11276  const auto *NewTA = NewFD->getAttr<TargetAttr>();
11277  const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11278  MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11279  // Disallow mixing of multiversioning types.
11280  if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
11281  S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11282  S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11283  NewFD->setInvalidDecl();
11284  return true;
11285  }
11286 
11287  ParsedTargetAttr NewParsed;
11288  if (NewTA) {
11289  NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11290  NewTA->getFeaturesStr());
11291  llvm::sort(NewParsed.Features);
11292  }
11294  if (NewTVA) {
11295  NewTVA->getFeatures(NewFeats);
11296  llvm::sort(NewFeats);
11297  }
11298 
11299  bool UseMemberUsingDeclRules =
11300  S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11301 
11302  bool MayNeedOverloadableChecks =
11304 
11305  // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11306  // of a previous member of the MultiVersion set.
11307  for (NamedDecl *ND : Previous) {
11308  FunctionDecl *CurFD = ND->getAsFunction();
11309  if (!CurFD || CurFD->isInvalidDecl())
11310  continue;
11311  if (MayNeedOverloadableChecks &&
11312  S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11313  continue;
11314 
11315  if (NewMVKind == MultiVersionKind::None &&
11316  OldMVKind == MultiVersionKind::TargetVersion) {
11317  NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11318  S.Context, "default", NewFD->getSourceRange(),
11320  NewFD->setIsMultiVersion();
11321  NewMVKind = MultiVersionKind::TargetVersion;
11322  if (!NewTVA) {
11323  NewTVA = NewFD->getAttr<TargetVersionAttr>();
11324  NewTVA->getFeatures(NewFeats);
11325  llvm::sort(NewFeats);
11326  }
11327  }
11328 
11329  switch (NewMVKind) {
11331  assert(OldMVKind == MultiVersionKind::TargetClones &&
11332  "Only target_clones can be omitted in subsequent declarations");
11333  break;
11334  case MultiVersionKind::Target: {
11335  const auto *CurTA = CurFD->getAttr<TargetAttr>();
11336  if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11337  NewFD->setIsMultiVersion();
11338  Redeclaration = true;
11339  OldDecl = ND;
11340  return false;
11341  }
11342 
11343  ParsedTargetAttr CurParsed =
11345  CurTA->getFeaturesStr());
11346  llvm::sort(CurParsed.Features);
11347  if (CurParsed == NewParsed) {
11348  S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11349  S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11350  NewFD->setInvalidDecl();
11351  return true;
11352  }
11353  break;
11354  }
11356  const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>();
11357  if (CurTVA->getName() == NewTVA->getName()) {
11358  NewFD->setIsMultiVersion();
11359  Redeclaration = true;
11360  OldDecl = ND;
11361  return false;
11362  }
11364  if (CurTVA) {
11365  CurTVA->getFeatures(CurFeats);
11366  llvm::sort(CurFeats);
11367  }
11368  if (CurFeats == NewFeats) {
11369  S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11370  S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11371  NewFD->setInvalidDecl();
11372  return true;
11373  }
11374  break;
11375  }
11377  const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
11378  Redeclaration = true;
11379  OldDecl = CurFD;
11380  NewFD->setIsMultiVersion();
11381 
11382  if (CurClones && NewClones &&
11383  (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11384  !std::equal(CurClones->featuresStrs_begin(),
11385  CurClones->featuresStrs_end(),
11386  NewClones->featuresStrs_begin()))) {
11387  S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11388  S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11389  NewFD->setInvalidDecl();
11390  return true;
11391  }
11392 
11393  return false;
11394  }
11397  const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11398  const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11399  // Handle CPUDispatch/CPUSpecific versions.
11400  // Only 1 CPUDispatch function is allowed, this will make it go through
11401  // the redeclaration errors.
11402  if (NewMVKind == MultiVersionKind::CPUDispatch &&
11403  CurFD->hasAttr<CPUDispatchAttr>()) {
11404  if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11405  std::equal(
11406  CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11407  NewCPUDisp->cpus_begin(),
11408  [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11409  return Cur->getName() == New->getName();
11410  })) {
11411  NewFD->setIsMultiVersion();
11412  Redeclaration = true;
11413  OldDecl = ND;
11414  return false;
11415  }
11416 
11417  // If the declarations don't match, this is an error condition.
11418  S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11419  S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11420  NewFD->setInvalidDecl();
11421  return true;
11422  }
11423  if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11424  if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11425  std::equal(
11426  CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11427  NewCPUSpec->cpus_begin(),
11428  [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11429  return Cur->getName() == New->getName();
11430  })) {
11431  NewFD->setIsMultiVersion();
11432  Redeclaration = true;
11433  OldDecl = ND;
11434  return false;
11435  }
11436 
11437  // Only 1 version of CPUSpecific is allowed for each CPU.
11438  for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11439  for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11440  if (CurII == NewII) {
11441  S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11442  << NewII;
11443  S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11444  NewFD->setInvalidDecl();
11445  return true;
11446  }
11447  }
11448  }
11449  }
11450  break;
11451  }
11452  }
11453  }
11454 
11455  // Else, this is simply a non-redecl case. Checking the 'value' is only
11456  // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11457  // handled in the attribute adding step.
11458  if ((NewMVKind == MultiVersionKind::TargetVersion ||
11459  NewMVKind == MultiVersionKind::Target) &&
11460  CheckMultiVersionValue(S, NewFD)) {
11461  NewFD->setInvalidDecl();
11462  return true;
11463  }
11464 
11465  if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11466  !OldFD->isMultiVersion(), NewMVKind)) {
11467  NewFD->setInvalidDecl();
11468  return true;
11469  }
11470 
11471  // Permit forward declarations in the case where these two are compatible.
11472  if (!OldFD->isMultiVersion()) {
11473  OldFD->setIsMultiVersion();
11474  NewFD->setIsMultiVersion();
11475  Redeclaration = true;
11476  OldDecl = OldFD;
11477  return false;
11478  }
11479 
11480  NewFD->setIsMultiVersion();
11481  Redeclaration = false;
11482  OldDecl = nullptr;
11483  Previous.clear();
11484  return false;
11485 }
11486 
11487 /// Check the validity of a mulitversion function declaration.
11488 /// Also sets the multiversion'ness' of the function itself.
11489 ///
11490 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11491 ///
11492 /// Returns true if there was an error, false otherwise.
11494  bool &Redeclaration, NamedDecl *&OldDecl,
11496  const auto *NewTA = NewFD->getAttr<TargetAttr>();
11497  const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11498  const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11499  const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11500  const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11501  MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11502 
11503  // Main isn't allowed to become a multiversion function, however it IS
11504  // permitted to have 'main' be marked with the 'target' optimization hint,
11505  // for 'target_version' only default is allowed.
11506  if (NewFD->isMain()) {
11507  if (MVKind != MultiVersionKind::None &&
11508  !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11509  !(MVKind == MultiVersionKind::TargetVersion &&
11510  NewTVA->isDefaultVersion())) {
11511  S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11512  NewFD->setInvalidDecl();
11513  return true;
11514  }
11515  return false;
11516  }
11517 
11518  if (!OldDecl || !OldDecl->getAsFunction() ||
11519  OldDecl->getDeclContext()->getRedeclContext() !=
11520  NewFD->getDeclContext()->getRedeclContext()) {
11521  // If there's no previous declaration, AND this isn't attempting to cause
11522  // multiversioning, this isn't an error condition.
11523  if (MVKind == MultiVersionKind::None)
11524  return false;
11525  return CheckMultiVersionFirstFunction(S, NewFD);
11526  }
11527 
11528  FunctionDecl *OldFD = OldDecl->getAsFunction();
11529 
11530  if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) {
11531  // No target_version attributes mean default
11532  if (!NewTVA) {
11533  const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11534  if (OldTVA) {
11535  NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11536  S.Context, "default", NewFD->getSourceRange(),
11538  NewFD->setIsMultiVersion();
11539  OldFD->setIsMultiVersion();
11540  OldDecl = OldFD;
11541  Redeclaration = true;
11542  return true;
11543  }
11544  }
11545  return false;
11546  }
11547 
11548  // Multiversioned redeclarations aren't allowed to omit the attribute, except
11549  // for target_clones and target_version.
11550  if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11553  S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11555  NewFD->setInvalidDecl();
11556  return true;
11557  }
11558 
11559  if (!OldFD->isMultiVersion()) {
11560  switch (MVKind) {
11563  return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, Redeclaration,
11564  OldDecl, Previous);
11566  if (OldFD->isUsed(false)) {
11567  NewFD->setInvalidDecl();
11568  return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11569  }
11570  OldFD->setIsMultiVersion();
11571  break;
11572 
11576  break;
11577  }
11578  }
11579 
11580  // At this point, we have a multiversion function decl (in OldFD) AND an
11581  // appropriate attribute in the current function decl. Resolve that these are
11582  // still compatible with previous declarations.
11583  return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewCPUDisp,
11584  NewCPUSpec, NewClones, Redeclaration,
11585  OldDecl, Previous);
11586 }
11587 
11588 /// Perform semantic checking of a new function declaration.
11589 ///
11590 /// Performs semantic analysis of the new function declaration
11591 /// NewFD. This routine performs all semantic checking that does not
11592 /// require the actual declarator involved in the declaration, and is
11593 /// used both for the declaration of functions as they are parsed
11594 /// (called via ActOnDeclarator) and for the declaration of functions
11595 /// that have been instantiated via C++ template instantiation (called
11596 /// via InstantiateDecl).
11597 ///
11598 /// \param IsMemberSpecialization whether this new function declaration is
11599 /// a member specialization (that replaces any definition provided by the
11600 /// previous declaration).
11601 ///
11602 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11603 ///
11604 /// \returns true if the function declaration is a redeclaration.
11607  bool IsMemberSpecialization,
11608  bool DeclIsDefn) {
11609  assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11610  "Variably modified return types are not handled here");
11611 
11612  // Determine whether the type of this function should be merged with
11613  // a previous visible declaration. This never happens for functions in C++,
11614  // and always happens in C if the previous declaration was visible.
11615  bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11616  !Previous.isShadowed();
11617 
11618  bool Redeclaration = false;
11619  NamedDecl *OldDecl = nullptr;
11620  bool MayNeedOverloadableChecks = false;
11621 
11622  // Merge or overload the declaration with an existing declaration of
11623  // the same name, if appropriate.
11624  if (!Previous.empty()) {
11625  // Determine whether NewFD is an overload of PrevDecl or
11626  // a declaration that requires merging. If it's an overload,
11627  // there's no more work to do here; we'll just add the new
11628  // function to the scope.
11629  if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11630  NamedDecl *Candidate = Previous.getRepresentativeDecl();
11631  if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11632  Redeclaration = true;
11633  OldDecl = Candidate;
11634  }
11635  } else {
11636  MayNeedOverloadableChecks = true;
11637  switch (CheckOverload(S, NewFD, Previous, OldDecl,
11638  /*NewIsUsingDecl*/ false)) {
11639  case Ovl_Match:
11640  Redeclaration = true;
11641  break;
11642 
11643  case Ovl_NonFunction:
11644  Redeclaration = true;
11645  break;
11646 
11647  case Ovl_Overload:
11648  Redeclaration = false;
11649  break;
11650  }
11651  }
11652  }
11653 
11654  // Check for a previous extern "C" declaration with this name.
11655  if (!Redeclaration &&
11657  if (!Previous.empty()) {
11658  // This is an extern "C" declaration with the same name as a previous
11659  // declaration, and thus redeclares that entity...
11660  Redeclaration = true;
11661  OldDecl = Previous.getFoundDecl();
11662  MergeTypeWithPrevious = false;
11663 
11664  // ... except in the presence of __attribute__((overloadable)).
11665  if (OldDecl->hasAttr<OverloadableAttr>() ||
11666  NewFD->hasAttr<OverloadableAttr>()) {
11667  if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11668  MayNeedOverloadableChecks = true;
11669  Redeclaration = false;
11670  OldDecl = nullptr;
11671  }
11672  }
11673  }
11674  }
11675 
11676  if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11677  return Redeclaration;
11678 
11679  // PPC MMA non-pointer types are not allowed as function return types.
11680  if (Context.getTargetInfo().getTriple().isPPC64() &&
11681  CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11682  NewFD->setInvalidDecl();
11683  }
11684 
11685  // C++11 [dcl.constexpr]p8:
11686  // A constexpr specifier for a non-static member function that is not
11687  // a constructor declares that member function to be const.
11688  //
11689  // This needs to be delayed until we know whether this is an out-of-line
11690  // definition of a static member function.
11691  //
11692  // This rule is not present in C++1y, so we produce a backwards
11693  // compatibility warning whenever it happens in C++11.
11694  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11695  if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11696  !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11697  !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11698  CXXMethodDecl *OldMD = nullptr;
11699  if (OldDecl)
11700  OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11701  if (!OldMD || !OldMD->isStatic()) {
11702  const FunctionProtoType *FPT =
11703  MD->getType()->castAs<FunctionProtoType>();
11705  EPI.TypeQuals.addConst();
11706  MD->setType(Context.getFunctionType(FPT->getReturnType(),
11707  FPT->getParamTypes(), EPI));
11708 
11709  // Warn that we did this, if we're not performing template instantiation.
11710  // In that case, we'll have warned already when the template was defined.
11711  if (!inTemplateInstantiation()) {
11712  SourceLocation AddConstLoc;
11713  if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11715  AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11716 
11717  Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11718  << FixItHint::CreateInsertion(AddConstLoc, " const");
11719  }
11720  }
11721  }
11722 
11723  if (Redeclaration) {
11724  // NewFD and OldDecl represent declarations that need to be
11725  // merged.
11726  if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11727  DeclIsDefn)) {
11728  NewFD->setInvalidDecl();
11729  return Redeclaration;
11730  }
11731 
11732  Previous.clear();
11733  Previous.addDecl(OldDecl);
11734 
11735  if (FunctionTemplateDecl *OldTemplateDecl =
11736  dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11737  auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11738  FunctionTemplateDecl *NewTemplateDecl
11739  = NewFD->getDescribedFunctionTemplate();
11740  assert(NewTemplateDecl && "Template/non-template mismatch");
11741 
11742  // The call to MergeFunctionDecl above may have created some state in
11743  // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11744  // can add it as a redeclaration.
11745  NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11746 
11747  NewFD->setPreviousDeclaration(OldFD);
11748  if (NewFD->isCXXClassMember()) {
11749  NewFD->setAccess(OldTemplateDecl->getAccess());
11750  NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11751  }
11752 
11753  // If this is an explicit specialization of a member that is a function
11754  // template, mark it as a member specialization.
11755  if (IsMemberSpecialization &&
11756  NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11757  NewTemplateDecl->setMemberSpecialization();
11758  assert(OldTemplateDecl->isMemberSpecialization());
11759  // Explicit specializations of a member template do not inherit deleted
11760  // status from the parent member template that they are specializing.
11761  if (OldFD->isDeleted()) {
11762  // FIXME: This assert will not hold in the presence of modules.
11763  assert(OldFD->getCanonicalDecl() == OldFD);
11764  // FIXME: We need an update record for this AST mutation.
11765  OldFD->setDeletedAsWritten(false);
11766  }
11767  }
11768 
11769  } else {
11770  if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11771  auto *OldFD = cast<FunctionDecl>(OldDecl);
11772  // This needs to happen first so that 'inline' propagates.
11773  NewFD->setPreviousDeclaration(OldFD);
11774  if (NewFD->isCXXClassMember())
11775  NewFD->setAccess(OldFD->getAccess());
11776  }
11777  }
11778  } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11779  !NewFD->getAttr<OverloadableAttr>()) {
11780  assert((Previous.empty() ||
11781  llvm::any_of(Previous,
11782  [](const NamedDecl *ND) {
11783  return ND->hasAttr<OverloadableAttr>();
11784  })) &&
11785  "Non-redecls shouldn't happen without overloadable present");
11786 
11787  auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11788  const auto *FD = dyn_cast<FunctionDecl>(ND);
11789  return FD && !FD->hasAttr<OverloadableAttr>();
11790  });
11791 
11792  if (OtherUnmarkedIter != Previous.end()) {
11793  Diag(NewFD->getLocation(),
11794  diag::err_attribute_overloadable_multiple_unmarked_overloads);
11795  Diag((*OtherUnmarkedIter)->getLocation(),
11796  diag::note_attribute_overloadable_prev_overload)
11797  << false;
11798 
11799  NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11800  }
11801  }
11802 
11803  if (LangOpts.OpenMP)
11804  ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11805 
11806  // Semantic checking for this function declaration (in isolation).
11807 
11808  if (getLangOpts().CPlusPlus) {
11809  // C++-specific checks.
11810  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11811  CheckConstructor(Constructor);
11812  } else if (CXXDestructorDecl *Destructor =
11813  dyn_cast<CXXDestructorDecl>(NewFD)) {
11814  // We check here for invalid destructor names.
11815  // If we have a friend destructor declaration that is dependent, we can't
11816  // diagnose right away because cases like this are still valid:
11817  // template <class T> struct A { friend T::X::~Y(); };
11818  // struct B { struct Y { ~Y(); }; using X = Y; };
11819  // template struct A<B>;
11820  if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
11821  !Destructor->getThisType()->isDependentType()) {
11822  CXXRecordDecl *Record = Destructor->getParent();
11823  QualType ClassType = Context.getTypeDeclType(Record);
11824 
11826  Context.getCanonicalType(ClassType));
11827  if (NewFD->getDeclName() != Name) {
11828  Diag(NewFD->getLocation(), diag::err_destructor_name);
11829  NewFD->setInvalidDecl();
11830  return Redeclaration;
11831  }
11832  }
11833  } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11834  if (auto *TD = Guide->getDescribedFunctionTemplate())
11835  CheckDeductionGuideTemplate(TD);
11836 
11837  // A deduction guide is not on the list of entities that can be
11838  // explicitly specialized.
11839  if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11840  Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11841  << /*explicit specialization*/ 1;
11842  }
11843 
11844  // Find any virtual functions that this function overrides.
11845  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11846  if (!Method->isFunctionTemplateSpecialization() &&
11847  !Method->getDescribedFunctionTemplate() &&
11848  Method->isCanonicalDecl()) {
11849  AddOverriddenMethods(Method->getParent(), Method);
11850  }
11851  if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11852  // C++2a [class.virtual]p6
11853  // A virtual method shall not have a requires-clause.
11855  diag::err_constrained_virtual_method);
11856 
11857  if (Method->isStatic())
11858  checkThisInStaticMemberFunctionType(Method);
11859  }
11860 
11861  // C++20: dcl.decl.general p4:
11862  // The optional requires-clause ([temp.pre]) in an init-declarator or
11863  // member-declarator shall be present only if the declarator declares a
11864  // templated function ([dcl.fct]).
11865  if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
11866  if (!NewFD->isTemplated() && !NewFD->isTemplateInstantiation())
11867  Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
11868  }
11869 
11870  if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11871  ActOnConversionDeclarator(Conversion);
11872 
11873  // Extra checking for C++ overloaded operators (C++ [over.oper]).
11874  if (NewFD->isOverloadedOperator() &&
11875  CheckOverloadedOperatorDeclaration(NewFD)) {
11876  NewFD->setInvalidDecl();
11877  return Redeclaration;
11878  }
11879 
11880  // Extra checking for C++0x literal operators (C++0x [over.literal]).
11881  if (NewFD->getLiteralIdentifier() &&
11882  CheckLiteralOperatorDeclaration(NewFD)) {
11883  NewFD->setInvalidDecl();
11884  return Redeclaration;
11885  }
11886 
11887  // In C++, check default arguments now that we have merged decls. Unless
11888  // the lexical context is the class, because in this case this is done
11889  // during delayed parsing anyway.
11890  if (!CurContext->isRecord())
11891  CheckCXXDefaultArguments(NewFD);
11892 
11893  // If this function is declared as being extern "C", then check to see if
11894  // the function returns a UDT (class, struct, or union type) that is not C
11895  // compatible, and if it does, warn the user.
11896  // But, issue any diagnostic on the first declaration only.
11897  if (Previous.empty() && NewFD->isExternC()) {
11898  QualType R = NewFD->getReturnType();
11899  if (R->isIncompleteType() && !R->isVoidType())
11900  Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11901  << NewFD << R;
11902  else if (!R.isPODType(Context) && !R->isVoidType() &&
11903  !R->isObjCObjectPointerType())
11904  Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11905  }
11906 
11907  // C++1z [dcl.fct]p6:
11908  // [...] whether the function has a non-throwing exception-specification
11909  // [is] part of the function type
11910  //
11911  // This results in an ABI break between C++14 and C++17 for functions whose
11912  // declared type includes an exception-specification in a parameter or
11913  // return type. (Exception specifications on the function itself are OK in
11914  // most cases, and exception specifications are not permitted in most other
11915  // contexts where they could make it into a mangling.)
11916  if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11917  auto HasNoexcept = [&](QualType T) -> bool {
11918  // Strip off declarator chunks that could be between us and a function
11919  // type. We don't need to look far, exception specifications are very
11920  // restricted prior to C++17.
11921  if (auto *RT = T->getAs<ReferenceType>())
11922  T = RT->getPointeeType();
11923  else if (T->isAnyPointerType())
11924  T = T->getPointeeType();
11925  else if (auto *MPT = T->getAs<MemberPointerType>())
11926  T = MPT->getPointeeType();
11927  if (auto *FPT = T->getAs<FunctionProtoType>())
11928  if (FPT->isNothrow())
11929  return true;
11930  return false;
11931  };
11932 
11933  auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11934  bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11935  for (QualType T : FPT->param_types())
11936  AnyNoexcept |= HasNoexcept(T);
11937  if (AnyNoexcept)
11938  Diag(NewFD->getLocation(),
11939  diag::warn_cxx17_compat_exception_spec_in_signature)
11940  << NewFD;
11941  }
11942 
11943  if (!Redeclaration && LangOpts.CUDA)
11944  checkCUDATargetOverload(NewFD, Previous);
11945  }
11946  return Redeclaration;
11947 }
11948 
11949 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11950  // C++11 [basic.start.main]p3:
11951  // A program that [...] declares main to be inline, static or
11952  // constexpr is ill-formed.
11953  // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
11954  // appear in a declaration of main.
11955  // static main is not an error under C99, but we should warn about it.
11956  // We accept _Noreturn main as an extension.
11957  if (FD->getStorageClass() == SC_Static)
11958  Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11959  ? diag::err_static_main : diag::warn_static_main)
11961  if (FD->isInlineSpecified())
11962  Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11964  if (DS.isNoreturnSpecified()) {
11965  SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11966  SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11967  Diag(NoreturnLoc, diag::ext_noreturn_main);
11968  Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11969  << FixItHint::CreateRemoval(NoreturnRange);
11970  }
11971  if (FD->isConstexpr()) {
11972  Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11973  << FD->isConsteval()
11976  }
11977 
11978  if (getLangOpts().OpenCL) {
11979  Diag(FD->getLocation(), diag::err_opencl_no_main)
11980  << FD->hasAttr<OpenCLKernelAttr>();
11981  FD->setInvalidDecl();
11982  return;
11983  }
11984 
11985  // Functions named main in hlsl are default entries, but don't have specific
11986  // signatures they are required to conform to.
11987  if (getLangOpts().HLSL)
11988  return;
11989 
11990  QualType T = FD->getType();
11991  assert(T->isFunctionType() && "function decl is not of function type");
11992  const FunctionType* FT = T->castAs<FunctionType>();
11993 
11994  // Set default calling convention for main()
11995  if (FT->getCallConv() != CC_C) {
11996  FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11997  FD->setType(QualType(FT, 0));
11998  T = Context.getCanonicalType(FD->getType());
11999  }
12000 
12001  if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12002  // In C with GNU extensions we allow main() to have non-integer return
12003  // type, but we should warn about the extension, and we disable the
12004  // implicit-return-zero rule.
12005 
12006  // GCC in C mode accepts qualified 'int'.
12007  if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12008  FD->setHasImplicitReturnZero(true);
12009  else {
12010  Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12011  SourceRange RTRange = FD->getReturnTypeSourceRange();
12012  if (RTRange.isValid())
12013  Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12014  << FixItHint::CreateReplacement(RTRange, "int");
12015  }
12016  } else {
12017  // In C and C++, main magically returns 0 if you fall off the end;
12018  // set the flag which tells us that.
12019  // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12020 
12021  // All the standards say that main() should return 'int'.
12022  if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12023  FD->setHasImplicitReturnZero(true);
12024  else {
12025  // Otherwise, this is just a flat-out error.
12026  SourceRange RTRange = FD->getReturnTypeSourceRange();
12027  Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12028  << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12029  : FixItHint());
12030  FD->setInvalidDecl(true);
12031  }
12032  }
12033 
12034  // Treat protoless main() as nullary.
12035  if (isa<FunctionNoProtoType>(FT)) return;
12036 
12037  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12038  unsigned nparams = FTP->getNumParams();
12039  assert(FD->getNumParams() == nparams);
12040 
12041  bool HasExtraParameters = (nparams > 3);
12042 
12043  if (FTP->isVariadic()) {
12044  Diag(FD->getLocation(), diag::ext_variadic_main);
12045  // FIXME: if we had information about the location of the ellipsis, we
12046  // could add a FixIt hint to remove it as a parameter.
12047  }
12048 
12049  // Darwin passes an undocumented fourth argument of type char**. If
12050  // other platforms start sprouting these, the logic below will start
12051  // getting shifty.
12052  if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12053  HasExtraParameters = false;
12054 
12055  if (HasExtraParameters) {
12056  Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12057  FD->setInvalidDecl(true);
12058  nparams = 3;
12059  }
12060 
12061  // FIXME: a lot of the following diagnostics would be improved
12062  // if we had some location information about types.
12063 
12064  QualType CharPP =
12065  Context.getPointerType(Context.getPointerType(Context.CharTy));
12066  QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12067 
12068  for (unsigned i = 0; i < nparams; ++i) {
12069  QualType AT = FTP->getParamType(i);
12070 
12071  bool mismatch = true;
12072 
12073  if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12074  mismatch = false;
12075  else if (Expected[i] == CharPP) {
12076  // As an extension, the following forms are okay:
12077  // char const **
12078  // char const * const *
12079  // char * const *
12080 
12081  QualifierCollector qs;
12082  const PointerType* PT;
12083  if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12084  (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12085  Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12086  Context.CharTy)) {
12087  qs.removeConst();
12088  mismatch = !qs.empty();
12089  }
12090  }
12091 
12092  if (mismatch) {
12093  Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12094  // TODO: suggest replacing given type with expected type
12095  FD->setInvalidDecl(true);
12096  }
12097  }
12098 
12099  if (nparams == 1 && !FD->isInvalidDecl()) {
12100  Diag(FD->getLocation(), diag::warn_main_one_arg);
12101  }
12102 
12103  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12104  Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12105  FD->setInvalidDecl();
12106  }
12107 }
12108 
12109 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12110 
12111  // Default calling convention for main and wmain is __cdecl
12112  if (FD->getName() == "main" || FD->getName() == "wmain")
12113  return false;
12114 
12115  // Default calling convention for MinGW is __cdecl
12116  const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12117  if (T.isWindowsGNUEnvironment())
12118  return false;
12119 
12120  // Default calling convention for WinMain, wWinMain and DllMain
12121  // is __stdcall on 32 bit Windows
12122  if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12123  return true;
12124 
12125  return false;
12126 }
12127 
12129  QualType T = FD->getType();
12130  assert(T->isFunctionType() && "function decl is not of function type");
12131  const FunctionType *FT = T->castAs<FunctionType>();
12132 
12133  // Set an implicit return of 'zero' if the function can return some integral,
12134  // enumeration, pointer or nullptr type.
12136  FT->getReturnType()->isAnyPointerType() ||
12137  FT->getReturnType()->isNullPtrType())
12138  // DllMain is exempt because a return value of zero means it failed.
12139  if (FD->getName() != "DllMain")
12140  FD->setHasImplicitReturnZero(true);
12141 
12142  // Explicity specified calling conventions are applied to MSVC entry points
12143  if (!hasExplicitCallingConv(T)) {
12144  if (isDefaultStdCall(FD, *this)) {
12145  if (FT->getCallConv() != CC_X86StdCall) {
12146  FT = Context.adjustFunctionType(
12148  FD->setType(QualType(FT, 0));
12149  }
12150  } else if (FT->getCallConv() != CC_C) {
12151  FT = Context.adjustFunctionType(FT,
12153  FD->setType(QualType(FT, 0));
12154  }
12155  }
12156 
12157  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12158  Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12159  FD->setInvalidDecl();
12160  }
12161 }
12162 
12164  auto &TargetInfo = getASTContext().getTargetInfo();
12165  auto const Triple = TargetInfo.getTriple();
12166  switch (Triple.getEnvironment()) {
12167  default:
12168  // FIXME: check all shader profiles.
12169  break;
12170  case llvm::Triple::EnvironmentType::Compute:
12171  if (!FD->hasAttr<HLSLNumThreadsAttr>()) {
12172  Diag(FD->getLocation(), diag::err_hlsl_missing_numthreads)
12173  << Triple.getEnvironmentName();
12174  FD->setInvalidDecl();
12175  }
12176  break;
12177  }
12178 
12179  for (const auto *Param : FD->parameters()) {
12180  if (!Param->hasAttr<HLSLAnnotationAttr>()) {
12181  // FIXME: Handle struct parameters where annotations are on struct fields.
12182  // See: https://github.com/llvm/llvm-project/issues/57875
12183  Diag(FD->getLocation(), diag::err_hlsl_missing_semantic_annotation);
12184  Diag(Param->getLocation(), diag::note_previous_decl) << Param;
12185  FD->setInvalidDecl();
12186  }
12187  }
12188  // FIXME: Verify return type semantic annotation.
12189 }
12190 
12192  // FIXME: Need strict checking. In C89, we need to check for
12193  // any assignment, increment, decrement, function-calls, or
12194  // commas outside of a sizeof. In C99, it's the same list,
12195  // except that the aforementioned are allowed in unevaluated
12196  // expressions. Everything else falls under the
12197  // "may accept other forms of constant expressions" exception.
12198  //
12199  // Regular C++ code will not end up here (exceptions: language extensions,
12200  // OpenCL C++ etc), so the constant expression rules there don't matter.
12201  if (Init->isValueDependent()) {
12202  assert(Init->containsErrors() &&
12203  "Dependent code should only occur in error-recovery path.");
12204  return true;
12205  }
12206  const Expr *Culprit;
12207  if (Init->isConstantInitializer(Context, false, &Culprit))
12208  return false;
12209  Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
12210  << Culprit->getSourceRange();
12211  return true;
12212 }
12213 
12214 namespace {
12215  // Visits an initialization expression to see if OrigDecl is evaluated in
12216  // its own initialization and throws a warning if it does.
12217  class SelfReferenceChecker
12218  : public EvaluatedExprVisitor<SelfReferenceChecker> {
12219  Sema &S;
12220  Decl *OrigDecl;
12221  bool isRecordType;
12222  bool isPODType;
12223  bool isReferenceType;
12224 
12225  bool isInitList;
12226  llvm::SmallVector<unsigned, 4> InitFieldIndex;
12227 
12228  public:
12230 
12231  SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12232  S(S), OrigDecl(OrigDecl) {
12233  isPODType = false;
12234  isRecordType = false;
12235  isReferenceType = false;
12236  isInitList = false;
12237  if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12238  isPODType = VD->getType().isPODType(S.Context);
12239  isRecordType = VD->getType()->isRecordType();
12240  isReferenceType = VD->getType()->isReferenceType();
12241  }
12242  }
12243 
12244  // For most expressions, just call the visitor. For initializer lists,
12245  // track the index of the field being initialized since fields are
12246  // initialized in order allowing use of previously initialized fields.
12247  void CheckExpr(Expr *E) {
12248  InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12249  if (!InitList) {
12250  Visit(E);
12251  return;
12252  }
12253 
12254  // Track and increment the index here.
12255  isInitList = true;
12256  InitFieldIndex.push_back(0);
12257  for (auto *Child : InitList->children()) {
12258  CheckExpr(cast<Expr>(Child));
12259  ++InitFieldIndex.back();
12260  }
12261  InitFieldIndex.pop_back();
12262  }
12263 
12264  // Returns true if MemberExpr is checked and no further checking is needed.
12265  // Returns false if additional checking is required.
12266  bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12268  Expr *Base = E;
12269  bool ReferenceField = false;
12270 
12271  // Get the field members used.
12272  while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12273  FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12274  if (!FD)
12275  return false;
12276  Fields.push_back(FD);
12277  if (FD->getType()->isReferenceType())
12278  ReferenceField = true;
12279  Base = ME->getBase()->IgnoreParenImpCasts();
12280  }
12281 
12282  // Keep checking only if the base Decl is the same.
12283  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12284  if (!DRE || DRE->getDecl() != OrigDecl)
12285  return false;
12286 
12287  // A reference field can be bound to an unininitialized field.
12288  if (CheckReference && !ReferenceField)
12289  return true;
12290 
12291  // Convert FieldDecls to their index number.
12292  llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12293  for (const FieldDecl *I : llvm::reverse(Fields))
12294  UsedFieldIndex.push_back(I->getFieldIndex());
12295 
12296  // See if a warning is needed by checking the first difference in index
12297  // numbers. If field being used has index less than the field being
12298  // initialized, then the use is safe.
12299  for (auto UsedIter = UsedFieldIndex.begin(),
12300  UsedEnd = UsedFieldIndex.end(),
12301  OrigIter = InitFieldIndex.begin(),
12302  OrigEnd = InitFieldIndex.end();
12303  UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12304  if (*UsedIter < *OrigIter)
12305  return true;
12306  if (*UsedIter > *OrigIter)
12307  break;
12308  }
12309 
12310  // TODO: Add a different warning which will print the field names.
12311  HandleDeclRefExpr(DRE);
12312  return true;
12313  }
12314 
12315  // For most expressions, the cast is directly above the DeclRefExpr.
12316  // For conditional operators, the cast can be outside the conditional
12317  // operator if both expressions are DeclRefExpr's.
12318  void HandleValue(Expr *E) {
12319  E = E->IgnoreParens();
12320  if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12321  HandleDeclRefExpr(DRE);
12322  return;
12323  }
12324 
12325  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12326  Visit(CO->getCond());
12327  HandleValue(CO->getTrueExpr());
12328  HandleValue(CO->getFalseExpr());
12329  return;
12330  }
12331 
12332  if (BinaryConditionalOperator *BCO =
12333  dyn_cast<BinaryConditionalOperator>(E)) {
12334  Visit(BCO->getCond());
12335  HandleValue(BCO->getFalseExpr());
12336  return;
12337  }
12338 
12339  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12340  HandleValue(OVE->getSourceExpr());
12341  return;
12342  }
12343 
12344  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12345  if (BO->getOpcode() == BO_Comma) {
12346  Visit(BO->getLHS());
12347  HandleValue(BO->getRHS());
12348  return;
12349  }
12350  }
12351 
12352  if (isa<MemberExpr>(E)) {
12353  if (isInitList) {
12354  if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12355  false /*CheckReference*/))
12356  return;
12357  }
12358 
12359  Expr *Base = E->IgnoreParenImpCasts();
12360  while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12361  // Check for static member variables and don't warn on them.
12362  if (!isa<FieldDecl>(ME->getMemberDecl()))
12363  return;
12364  Base = ME->getBase()->IgnoreParenImpCasts();
12365  }
12366  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12367  HandleDeclRefExpr(DRE);
12368  return;
12369  }
12370 
12371  Visit(E);
12372  }
12373 
12374  // Reference types not handled in HandleValue are handled here since all
12375  // uses of references are bad, not just r-value uses.
12376  void VisitDeclRefExpr(DeclRefExpr *E) {
12377  if (isReferenceType)
12378  HandleDeclRefExpr(E);
12379  }
12380 
12381  void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12382  if (E->getCastKind() == CK_LValueToRValue) {
12383  HandleValue(E->getSubExpr());
12384  return;
12385  }
12386 
12387  Inherited::VisitImplicitCastExpr(E);
12388  }
12389 
12390  void VisitMemberExpr(MemberExpr *E) {
12391  if (isInitList) {
12392  if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12393  return;
12394  }
12395 
12396  // Don't warn on arrays since they can be treated as pointers.
12397  if (E->getType()->canDecayToPointerType()) return;
12398 
12399  // Warn when a non-static method call is followed by non-static member
12400  // field accesses, which is followed by a DeclRefExpr.
12401  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12402  bool Warn = (MD && !MD->isStatic());
12403  Expr *Base = E->getBase()->IgnoreParenImpCasts();
12404  while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12405  if (!isa<FieldDecl>(ME->getMemberDecl()))
12406  Warn = false;
12407  Base = ME->getBase()->IgnoreParenImpCasts();
12408  }
12409 
12410  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12411  if (Warn)
12412  HandleDeclRefExpr(DRE);
12413  return;
12414  }
12415 
12416  // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12417  // Visit that expression.
12418  Visit(Base);
12419  }
12420 
12421  void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12422  Expr *Callee = E->getCallee();
12423 
12424  if (isa<UnresolvedLookupExpr>(Callee))
12425  return Inherited::VisitCXXOperatorCallExpr(E);
12426 
12427  Visit(Callee);
12428  for (auto Arg: E->arguments())
12429  HandleValue(Arg->IgnoreParenImpCasts());
12430  }
12431 
12432  void VisitUnaryOperator(UnaryOperator *E) {
12433  // For POD record types, addresses of its own members are well-defined.
12434  if (E->getOpcode() == UO_AddrOf && isRecordType &&
12435  isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12436  if (!isPODType)
12437  HandleValue(E->getSubExpr());
12438  return;
12439  }
12440 
12441  if (E->isIncrementDecrementOp()) {
12442  HandleValue(E->getSubExpr());
12443  return;
12444  }
12445 
12446  Inherited::VisitUnaryOperator(E);
12447  }
12448 
12449  void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12450 
12451  void VisitCXXConstructExpr(CXXConstructExpr *E) {
12452  if (E->getConstructor()->isCopyConstructor()) {
12453  Expr *ArgExpr = E->getArg(0);
12454  if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12455  if (ILE->getNumInits() == 1)
12456  ArgExpr = ILE->getInit(0);
12457  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12458  if (ICE->getCastKind() == CK_NoOp)
12459  ArgExpr = ICE->getSubExpr();
12460  HandleValue(ArgExpr);
12461  return;
12462  }
12463  Inherited::VisitCXXConstructExpr(E);
12464  }
12465 
12466  void VisitCallExpr(CallExpr *E) {
12467  // Treat std::move as a use.
12468  if (E->isCallToStdMove()) {
12469  HandleValue(E->getArg(0));
12470  return;
12471  }
12472 
12473  Inherited::VisitCallExpr(E);
12474  }
12475 
12476  void VisitBinaryOperator(BinaryOperator *E) {
12477  if (E->isCompoundAssignmentOp()) {
12478  HandleValue(E->getLHS());
12479  Visit(E->getRHS());
12480  return;
12481  }
12482 
12483  Inherited::VisitBinaryOperator(E);
12484  }
12485 
12486  // A custom visitor for BinaryConditionalOperator is needed because the
12487  // regular visitor would check the condition and true expression separately
12488  // but both point to the same place giving duplicate diagnostics.
12489  void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12490  Visit(E->getCond());
12491  Visit(E->getFalseExpr());
12492  }
12493 
12494  void HandleDeclRefExpr(DeclRefExpr *DRE) {
12495  Decl* ReferenceDecl = DRE->getDecl();
12496  if (OrigDecl != ReferenceDecl) return;
12497  unsigned diag;
12498  if (isReferenceType) {
12499  diag = diag::warn_uninit_self_reference_in_reference_init;
12500  } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12501  diag = diag::warn_static_self_reference_in_init;
12502  } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12503  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12504  DRE->getDecl()->getType()->isRecordType()) {
12505  diag = diag::warn_uninit_self_reference_in_init;
12506  } else {
12507  // Local variables will be handled by the CFG analysis.
12508  return;
12509  }
12510 
12511  S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12512  S.PDiag(diag)
12513  << DRE->getDecl() << OrigDecl->getLocation()
12514  << DRE->getSourceRange());
12515  }
12516  };
12517 
12518  /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12519  static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12520  bool DirectInit) {
12521  // Parameters arguments are occassionially constructed with itself,
12522  // for instance, in recursive functions. Skip them.
12523  if (isa<ParmVarDecl>(OrigDecl))
12524  return;
12525 
12526  E = E->IgnoreParens();
12527 
12528  // Skip checking T a = a where T is not a record or reference type.
12529  // Doing so is a way to silence uninitialized warnings.
12530  if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12531  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12532  if (ICE->getCastKind() == CK_LValueToRValue)
12533  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12534  if (DRE->getDecl() == OrigDecl)
12535  return;
12536 
12537  SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12538  }
12539 } // end anonymous namespace
12540 
12541 namespace {
12542  // Simple wrapper to add the name of a variable or (if no variable is
12543  // available) a DeclarationName into a diagnostic.
12544  struct VarDeclOrName {
12545  VarDecl *VDecl;
12546  DeclarationName Name;
12547 
12548  friend const Sema::SemaDiagnosticBuilder &
12549  operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12550  return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12551  }
12552  };
12553 } // end anonymous namespace
12554 
12557  TypeSourceInfo *TSI,
12558  SourceRange Range, bool DirectInit,
12559  Expr *Init) {
12560  bool IsInitCapture = !VDecl;
12561  assert((!VDecl || !VDecl->isInitCapture()) &&
12562  "init captures are expected to be deduced prior to initialization");
12563 
12564  VarDeclOrName VN{VDecl, Name};
12565 
12567  assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12568 
12569  // C++11 [dcl.spec.auto]p3
12570  if (!Init) {
12571  assert(VDecl && "no init for init capture deduction?");
12572 
12573  // Except for class argument deduction, and then for an initializing
12574  // declaration only, i.e. no static at class scope or extern.
12575  if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12576  VDecl->hasExternalStorage() ||
12577  VDecl->isStaticDataMember()) {
12578  Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12579  << VDecl->getDeclName() << Type;
12580  return QualType();
12581  }
12582  }
12583 
12584  ArrayRef<Expr*> DeduceInits;
12585  if (Init)
12586  DeduceInits = Init;
12587 
12588  if (DirectInit) {
12589  if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
12590  DeduceInits = PL->exprs();
12591  }
12592 
12593  if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12594  assert(VDecl && "non-auto type for init capture deduction?");
12597  VDecl->getLocation(), DirectInit, Init);
12598  // FIXME: Initialization should not be taking a mutable list of inits.
12599  SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12600  return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12601  InitsCopy);
12602  }
12603 
12604  if (DirectInit) {
12605  if (auto *IL = dyn_cast<InitListExpr>(Init))
12606  DeduceInits = IL->inits();
12607  }
12608 
12609  // Deduction only works if we have exactly one source expression.
12610  if (DeduceInits.empty()) {
12611  // It isn't possible to write this directly, but it is possible to
12612  // end up in this situation with "auto x(some_pack...);"
12613  Diag(Init->getBeginLoc(), IsInitCapture
12614  ? diag::err_init_capture_no_expression
12615  : diag::err_auto_var_init_no_expression)
12616  << VN << Type << Range;
12617  return QualType();
12618  }
12619 
12620  if (DeduceInits.size() > 1) {
12621  Diag(DeduceInits[1]->getBeginLoc(),
12622  IsInitCapture ? diag::err_init_capture_multiple_expressions
12623  : diag::err_auto_var_init_multiple_expressions)
12624  << VN << Type << Range;
12625  return QualType();
12626  }
12627 
12628  Expr *DeduceInit = DeduceInits[0];
12629  if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12630  Diag(Init->getBeginLoc(), IsInitCapture
12631  ? diag::err_init_capture_paren_braces
12632  : diag::err_auto_var_init_paren_braces)
12633  << isa<InitListExpr>(Init) << VN << Type << Range;
12634  return QualType();
12635  }
12636 
12637  // Expressions default to 'id' when we're in a debugger.
12638  bool DefaultedAnyToId = false;
12639  if (getLangOpts().DebuggerCastResultToId &&
12640  Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12641  ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12642  if (Result.isInvalid()) {
12643  return QualType();
12644  }
12645  Init = Result.get();
12646  DefaultedAnyToId = true;
12647  }
12648 
12649  // C++ [dcl.decomp]p1:
12650  // If the assignment-expression [...] has array type A and no ref-qualifier
12651  // is present, e has type cv A
12652  if (VDecl && isa<DecompositionDecl>(VDecl) &&
12653  Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12654  DeduceInit->getType()->isConstantArrayType())
12655  return Context.getQualifiedType(DeduceInit->getType(),
12656  Type.getQualifiers());
12657 
12659  TemplateDeductionInfo Info(DeduceInit->getExprLoc());
12660  TemplateDeductionResult Result =
12661  DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
12662  if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed) {
12663  if (!IsInitCapture)
12664  DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12665  else if (isa<InitListExpr>(Init))
12666  Diag(Range.getBegin(),
12667  diag::err_init_capture_deduction_failure_from_init_list)
12668  << VN
12669  << (DeduceInit->getType().isNull() ? TSI->getType()
12670  : DeduceInit->getType())
12671  << DeduceInit->getSourceRange();
12672  else
12673  Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12674  << VN << TSI->getType()
12675  << (DeduceInit->getType().isNull() ? TSI->getType()
12676  : DeduceInit->getType())
12677  << DeduceInit->getSourceRange();
12678  }
12679 
12680  // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12681  // 'id' instead of a specific object type prevents most of our usual
12682  // checks.
12683  // We only want to warn outside of template instantiations, though:
12684  // inside a template, the 'id' could have come from a parameter.
12685  if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12686  !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12687  SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12688  Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12689  }
12690 
12691  return DeducedType;
12692 }
12693 
12694 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12695  Expr *Init) {
12696  assert(!Init || !Init->containsErrors());
12697  QualType DeducedType = deduceVarTypeFromInitializer(
12698  VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12699  VDecl->getSourceRange(), DirectInit, Init);
12700  if (DeducedType.isNull()) {
12701  VDecl->setInvalidDecl();
12702  return true;
12703  }
12704 
12705  VDecl->setType(DeducedType);
12706  assert(VDecl->isLinkageValid());
12707 
12708  // In ARC, infer lifetime.
12709  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12710  VDecl->setInvalidDecl();
12711 
12712  if (getLangOpts().OpenCL)
12713  deduceOpenCLAddressSpace(VDecl);
12714 
12715  // If this is a redeclaration, check that the type we just deduced matches
12716  // the previously declared type.
12717  if (VarDecl *Old = VDecl->getPreviousDecl()) {
12718  // We never need to merge the type, because we cannot form an incomplete
12719  // array of auto, nor deduce such a type.
12720  MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12721  }
12722 
12723  // Check the deduced type is valid for a variable declaration.
12724  CheckVariableDeclarationType(VDecl);
12725  return VDecl->isInvalidDecl();
12726 }
12727 
12729  SourceLocation Loc) {
12730  if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12731  Init = EWC->getSubExpr();
12732 
12733  if (auto *CE = dyn_cast<ConstantExpr>(Init))
12734  Init = CE->getSubExpr();
12735 
12736  QualType InitType = Init->getType();
12738  InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12739  "shouldn't be called if type doesn't have a non-trivial C struct");
12740  if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12741  for (auto *I : ILE->inits()) {
12742  if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12743  !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12744  continue;
12745  SourceLocation SL = I->getExprLoc();
12746  checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12747  }
12748  return;
12749  }
12750 
12751  if (isa<ImplicitValueInitExpr>(Init)) {
12753  checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12754  NTCUK_Init);
12755  } else {
12756  // Assume all other explicit initializers involving copying some existing
12757  // object.
12758  // TODO: ignore any explicit initializers where we can guarantee
12759  // copy-elision.
12760  if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12761  checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12762  }
12763 }
12764 
12765 namespace {
12766 
12767 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12768  // Ignore unavailable fields. A field can be marked as unavailable explicitly
12769  // in the source code or implicitly by the compiler if it is in a union
12770  // defined in a system header and has non-trivial ObjC ownership
12771  // qualifications. We don't want those fields to participate in determining
12772  // whether the containing union is non-trivial.
12773  return FD->hasAttr<UnavailableAttr>();
12774 }
12775 
12776 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12777  : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12778  void> {
12779  using Super =
12780  DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12781  void>;
12782 
12783  DiagNonTrivalCUnionDefaultInitializeVisitor(
12784  QualType OrigTy, SourceLocation OrigLoc,
12785  Sema::NonTrivialCUnionContext UseContext, Sema &S)
12786  : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12787 
12788  void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12789  const FieldDecl *FD, bool InNonTrivialUnion) {
12790  if (const auto *AT = S.Context.getAsArrayType(QT))
12791  return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12792  InNonTrivialUnion);
12793  return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12794  }
12795 
12796  void visitARCStrong(QualType QT, const FieldDecl *FD,
12797  bool InNonTrivialUnion) {
12798  if (InNonTrivialUnion)
12799  S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12800  << 1 << 0 << QT << FD->getName();
12801  }
12802 
12803  void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12804  if (InNonTrivialUnion)
12805  S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12806  << 1 << 0 << QT << FD->getName();
12807  }
12808 
12809  void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12810  const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12811  if (RD->isUnion()) {
12812  if (OrigLoc.isValid()) {
12813  bool IsUnion = false;
12814  if (auto *OrigRD = OrigTy->getAsRecordDecl())
12815  IsUnion = OrigRD->isUnion();
12816  S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12817  << 0 << OrigTy << IsUnion << UseContext;
12818  // Reset OrigLoc so that this diagnostic is emitted only once.
12819  OrigLoc = SourceLocation();
12820  }
12821  InNonTrivialUnion = true;
12822  }
12823 
12824  if (InNonTrivialUnion)
12825  S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12826  << 0 << 0 << QT.getUnqualifiedType() << "";
12827 
12828  for (const FieldDecl *FD : RD->fields())
12829  if (!shouldIgnoreForRecordTriviality(FD))
12830  asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12831  }
12832 
12833  void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12834 
12835  // The non-trivial C union type or the struct/union type that contains a
12836  // non-trivial C union.
12837  QualType OrigTy;
12838  SourceLocation OrigLoc;
12839  Sema::NonTrivialCUnionContext UseContext;
12840  Sema &S;
12841 };
12842 
12843 struct DiagNonTrivalCUnionDestructedTypeVisitor
12844  : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12845  using Super =
12847 
12848  DiagNonTrivalCUnionDestructedTypeVisitor(
12849  QualType OrigTy, SourceLocation OrigLoc,
12850  Sema::NonTrivialCUnionContext UseContext, Sema &S)
12851  : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12852 
12853  void visitWithKind(QualType::DestructionKind DK, QualType QT,
12854  const FieldDecl *FD, bool InNonTrivialUnion) {
12855  if (const auto *AT = S.Context.getAsArrayType(QT))
12856  return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12857  InNonTrivialUnion);
12858  return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12859  }
12860 
12861  void visitARCStrong(QualType QT, const FieldDecl *FD,
12862  bool InNonTrivialUnion) {
12863  if (InNonTrivialUnion)
12864  S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12865  << 1 << 1 << QT << FD->getName();
12866  }
12867 
12868  void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12869  if (InNonTrivialUnion)
12870  S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12871  << 1 << 1 << QT << FD->getName();
12872  }
12873 
12874  void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12875  const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12876  if (RD->isUnion()) {
12877  if (OrigLoc.isValid()) {
12878  bool IsUnion = false;
12879  if (auto *OrigRD = OrigTy->getAsRecordDecl())
12880  IsUnion = OrigRD->isUnion();
12881  S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12882  << 1 << OrigTy << IsUnion << UseContext;
12883  // Reset OrigLoc so that this diagnostic is emitted only once.
12884  OrigLoc = SourceLocation();
12885  }
12886  InNonTrivialUnion = true;
12887  }
12888 
12889  if (InNonTrivialUnion)
12890  S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12891  << 0 << 1 << QT.getUnqualifiedType() << "";
12892 
12893  for (const FieldDecl *FD : RD->fields())
12894  if (!shouldIgnoreForRecordTriviality(FD))
12895  asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12896  }
12897 
12898  void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12899  void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12900  bool InNonTrivialUnion) {}
12901 
12902  // The non-trivial C union type or the struct/union type that contains a
12903  // non-trivial C union.
12904  QualType OrigTy;
12905  SourceLocation OrigLoc;
12906  Sema::NonTrivialCUnionContext UseContext;
12907  Sema &S;
12908 };
12909 
12910 struct DiagNonTrivalCUnionCopyVisitor
12911  : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12913 
12914  DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12915  Sema::NonTrivialCUnionContext UseContext,
12916  Sema &S)
12917  : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12918 
12919  void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12920  const FieldDecl *FD, bool InNonTrivialUnion) {
12921  if (const auto *AT = S.Context.getAsArrayType(QT))
12922  return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12923  InNonTrivialUnion);
12924  return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12925  }
12926 
12927  void visitARCStrong(QualType QT, const FieldDecl *FD,
12928  bool InNonTrivialUnion) {
12929  if (InNonTrivialUnion)
12930  S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12931  << 1 << 2 << QT << FD->getName();
12932  }
12933 
12934  void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12935  if (InNonTrivialUnion)
12936  S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12937  << 1 << 2 << QT << FD->getName();
12938  }
12939 
12940  void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12941  const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12942  if (RD->isUnion()) {
12943  if (OrigLoc.isValid()) {
12944  bool IsUnion = false;
12945  if (auto *OrigRD = OrigTy->getAsRecordDecl())
12946  IsUnion = OrigRD->isUnion();
12947  S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12948  << 2 << OrigTy << IsUnion << UseContext;
12949  // Reset OrigLoc so that this diagnostic is emitted only once.
12950  OrigLoc = SourceLocation();
12951  }
12952  InNonTrivialUnion = true;
12953  }
12954 
12955  if (InNonTrivialUnion)
12956  S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12957  << 0 << 2 << QT.getUnqualifiedType() << "";
12958 
12959  for (const FieldDecl *FD : RD->fields())
12960  if (!shouldIgnoreForRecordTriviality(FD))
12961  asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12962  }
12963 
12964  void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12965  const FieldDecl *FD, bool InNonTrivialUnion) {}
12966  void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12967  void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12968  bool InNonTrivialUnion) {}
12969 
12970  // The non-trivial C union type or the struct/union type that contains a
12971  // non-trivial C union.
12972  QualType OrigTy;
12973  SourceLocation OrigLoc;
12974  Sema::NonTrivialCUnionContext UseContext;
12975  Sema &S;
12976 };
12977 
12978 } // namespace
12979 
12981  NonTrivialCUnionContext UseContext,
12982  unsigned NonTrivialKind) {
12986  "shouldn't be called if type doesn't have a non-trivial C union");
12987 
12988  if ((NonTrivialKind & NTCUK_Init) &&
12990  DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12991  .visit(QT, nullptr, false);
12992  if ((NonTrivialKind & NTCUK_Destruct) &&
12994  DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12995  .visit(QT, nullptr, false);
12996  if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12997  DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12998  .visit(QT, nullptr, false);
12999 }
13000 
13001 /// AddInitializerToDecl - Adds the initializer Init to the
13002 /// declaration dcl. If DirectInit is true, this is C++ direct
13003 /// initialization rather than copy initialization.
13004 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13005  // If there is no declaration, there was an error parsing it. Just ignore
13006  // the initializer.
13007  if (!RealDecl || RealDecl->isInvalidDecl()) {
13008  CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13009  return;
13010  }
13011 
13012  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13013  // Pure-specifiers are handled in ActOnPureSpecifier.
13014  Diag(Method->getLocation(), diag::err_member_function_initialization)
13015  << Method->getDeclName() << Init->getSourceRange();
13016  Method->setInvalidDecl();
13017  return;
13018  }
13019 
13020  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13021  if (!VDecl) {
13022  assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13023  Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13024  RealDecl->setInvalidDecl();
13025  return;
13026  }
13027 
13028  // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13029  if (VDecl->getType()->isUndeducedType()) {
13030  // Attempt typo correction early so that the type of the init expression can
13031  // be deduced based on the chosen correction if the original init contains a
13032  // TypoExpr.
13033  ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
13034  if (!Res.isUsable()) {
13035  // There are unresolved typos in Init, just drop them.
13036  // FIXME: improve the recovery strategy to preserve the Init.
13037  RealDecl->setInvalidDecl();
13038  return;
13039  }
13040  if (Res.get()->containsErrors()) {
13041  // Invalidate the decl as we don't know the type for recovery-expr yet.
13042  RealDecl->setInvalidDecl();
13043  VDecl->setInit(Res.get());
13044  return;
13045  }
13046  Init = Res.get();
13047 
13048  if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
13049  return;
13050  }
13051 
13052  // dllimport cannot be used on variable definitions.
13053  if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13054  Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13055  VDecl->setInvalidDecl();
13056  return;
13057  }
13058 
13059  // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13060  // the identifier has external or internal linkage, the declaration shall
13061  // have no initializer for the identifier.
13062  // C++14 [dcl.init]p5 is the same restriction for C++.
13063  if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13064  Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13065  VDecl->setInvalidDecl();
13066  return;
13067  }
13068 
13069  if (!VDecl->getType()->isDependentType()) {
13070  // A definition must end up with a complete type, which means it must be
13071  // complete with the restriction that an array type might be completed by
13072  // the initializer; note that later code assumes this restriction.
13073  QualType BaseDeclType = VDecl->getType();
13074  if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13075  BaseDeclType = Array->getElementType();
13076  if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13077  diag::err_typecheck_decl_incomplete_type)) {
13078  RealDecl->setInvalidDecl();
13079  return;
13080  }
13081 
13082  // The variable can not have an abstract class type.
13083  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13084  diag::err_abstract_type_in_decl,
13085  AbstractVariableType))
13086  VDecl->setInvalidDecl();
13087  }
13088 
13089  // C++ [module.import/6] external definitions are not permitted in header
13090  // units.
13091  if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13092  !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13094  !VDecl->isInline() && !VDecl->isTemplated() &&
13095  !isa<VarTemplateSpecializationDecl>(VDecl)) {
13096  Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13097  VDecl->setInvalidDecl();
13098  }
13099 
13100  // If adding the initializer will turn this declaration into a definition,
13101  // and we already have a definition for this variable, diagnose or otherwise
13102  // handle the situation.
13103  if (VarDecl *Def = VDecl->getDefinition())
13104  if (Def != VDecl &&
13105  (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13107  checkVarDeclRedefinition(Def, VDecl))
13108  return;
13109 
13110  if (getLangOpts().CPlusPlus) {
13111  // C++ [class.static.data]p4
13112  // If a static data member is of const integral or const
13113  // enumeration type, its declaration in the class definition can
13114  // specify a constant-initializer which shall be an integral
13115  // constant expression (5.19). In that case, the member can appear
13116  // in integral constant expressions. The member shall still be
13117  // defined in a namespace scope if it is used in the program and the
13118  // namespace scope definition shall not contain an initializer.
13119  //
13120  // We already performed a redefinition check above, but for static
13121  // data members we also need to check whether there was an in-class
13122  // declaration with an initializer.
13123  if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13124  Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13125  << VDecl->getDeclName();
13126  Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13127  diag::note_previous_initializer)
13128  << 0;
13129  return;
13130  }
13131 
13132  if (VDecl->hasLocalStorage())
13133  setFunctionHasBranchProtectedScope();
13134 
13135  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
13136  VDecl->setInvalidDecl();
13137  return;
13138  }
13139  }
13140 
13141  // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13142  // a kernel function cannot be initialized."
13143  if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13144  Diag(VDecl->getLocation(), diag::err_local_cant_init);
13145  VDecl->setInvalidDecl();
13146  return;
13147  }
13148 
13149  // The LoaderUninitialized attribute acts as a definition (of undef).
13150  if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13151  Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13152  VDecl->setInvalidDecl();
13153  return;
13154  }
13155 
13156  // Get the decls type and save a reference for later, since
13157  // CheckInitializerTypes may change it.
13158  QualType DclT = VDecl->getType(), SavT = DclT;
13159 
13160  // Expressions default to 'id' when we're in a debugger
13161  // and we are assigning it to a variable of Objective-C pointer type.
13162  if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13163  Init->getType() == Context.UnknownAnyTy) {
13164  ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
13165  if (Result.isInvalid()) {
13166  VDecl->setInvalidDecl();
13167  return;
13168  }
13169  Init = Result.get();
13170  }
13171 
13172  // Perform the initialization.
13173  ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13174  bool IsParenListInit = false;
13175  if (!VDecl->isInvalidDecl()) {
13178  VDecl->getLocation(), DirectInit, Init);
13179 
13180  MultiExprArg Args = Init;
13181  if (CXXDirectInit)
13182  Args = MultiExprArg(CXXDirectInit->getExprs(),
13183  CXXDirectInit->getNumExprs());
13184 
13185  // Try to correct any TypoExprs in the initialization arguments.
13186  for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13187  ExprResult Res = CorrectDelayedTyposInExpr(
13188  Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13189  [this, Entity, Kind](Expr *E) {
13190  InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13191  return Init.Failed() ? ExprError() : E;
13192  });
13193  if (Res.isInvalid()) {
13194  VDecl->setInvalidDecl();
13195  } else if (Res.get() != Args[Idx]) {
13196  Args[Idx] = Res.get();
13197  }
13198  }
13199  if (VDecl->isInvalidDecl())
13200  return;
13201 
13202  InitializationSequence InitSeq(*this, Entity, Kind, Args,
13203  /*TopLevelOfInitList=*/false,
13204  /*TreatUnavailableAsInvalid=*/false);
13205  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13206  if (Result.isInvalid()) {
13207  // If the provided initializer fails to initialize the var decl,
13208  // we attach a recovery expr for better recovery.
13209  auto RecoveryExpr =
13210  CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13211  if (RecoveryExpr.get())
13212  VDecl->setInit(RecoveryExpr.get());
13213  return;
13214  }
13215 
13216  Init = Result.getAs<Expr>();
13217  IsParenListInit = !InitSeq.steps().empty() &&
13218  InitSeq.step_begin()->Kind ==
13220  }
13221 
13222  // Check for self-references within variable initializers.
13223  // Variables declared within a function/method body (except for references)
13224  // are handled by a dataflow analysis.
13225  // This is undefined behavior in C++, but valid in C.
13226  if (getLangOpts().CPlusPlus)
13227  if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13228  VDecl->getType()->isReferenceType())
13229  CheckSelfReference(*this, RealDecl, Init, DirectInit);
13230 
13231  // If the type changed, it means we had an incomplete type that was
13232  // completed by the initializer. For example:
13233  // int ary[] = { 1, 3, 5 };
13234  // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13235  if (!VDecl->isInvalidDecl() && (DclT != SavT))
13236  VDecl->setType(DclT);
13237 
13238  if (!VDecl->isInvalidDecl()) {
13239  checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13240 
13241  if (VDecl->hasAttr<BlocksAttr>())
13242  checkRetainCycles(VDecl, Init);
13243 
13244  // It is safe to assign a weak reference into a strong variable.
13245  // Although this code can still have problems:
13246  // id x = self.weakProp;
13247  // id y = self.weakProp;
13248  // we do not warn to warn spuriously when 'x' and 'y' are on separate
13249  // paths through the function. This should be revisited if
13250  // -Wrepeated-use-of-weak is made flow-sensitive.
13251  if (FunctionScopeInfo *FSI = getCurFunction())
13252  if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13253  VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
13254  !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13255  Init->getBeginLoc()))
13256  FSI->markSafeWeakUse(Init);
13257  }
13258 
13259  // The initialization is usually a full-expression.
13260  //
13261  // FIXME: If this is a braced initialization of an aggregate, it is not
13262  // an expression, and each individual field initializer is a separate
13263  // full-expression. For instance, in:
13264  //
13265  // struct Temp { ~Temp(); };
13266  // struct S { S(Temp); };
13267  // struct T { S a, b; } t = { Temp(), Temp() }
13268  //
13269  // we should destroy the first Temp before constructing the second.
13270  ExprResult Result =
13271  ActOnFinishFullExpr(Init, VDecl->getLocation(),
13272  /*DiscardedValue*/ false, VDecl->isConstexpr());
13273  if (Result.isInvalid()) {
13274  VDecl->setInvalidDecl();
13275  return;
13276  }
13277  Init = Result.get();
13278 
13279  // Attach the initializer to the decl.
13280  VDecl->setInit(Init);
13281 
13282  if (VDecl->isLocalVarDecl()) {
13283  // Don't check the initializer if the declaration is malformed.
13284  if (VDecl->isInvalidDecl()) {
13285  // do nothing
13286 
13287  // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13288  // This is true even in C++ for OpenCL.
13289  } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13290  CheckForConstantInitializer(Init, DclT);
13291 
13292  // Otherwise, C++ does not restrict the initializer.
13293  } else if (getLangOpts().CPlusPlus) {
13294  // do nothing
13295 
13296  // C99 6.7.8p4: All the expressions in an initializer for an object that has
13297  // static storage duration shall be constant expressions or string literals.
13298  } else if (VDecl->getStorageClass() == SC_Static) {
13299  CheckForConstantInitializer(Init, DclT);
13300 
13301  // C89 is stricter than C99 for aggregate initializers.
13302  // C89 6.5.7p3: All the expressions [...] in an initializer list
13303  // for an object that has aggregate or union type shall be
13304  // constant expressions.
13305  } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13306  isa<InitListExpr>(Init)) {
13307  const Expr *Culprit;
13308  if (!Init->isConstantInitializer(Context, false, &Culprit)) {
13309  Diag(Culprit->getExprLoc(),
13310  diag::ext_aggregate_init_not_constant)
13311  << Culprit->getSourceRange();
13312  }
13313  }
13314 
13315  if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13316  if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13317  if (VDecl->hasLocalStorage())
13318  BE->getBlockDecl()->setCanAvoidCopyToHeap();
13319  } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13320  VDecl->getLexicalDeclContext()->isRecord()) {
13321  // This is an in-class initialization for a static data member, e.g.,
13322  //
13323  // struct S {
13324  // static const int value = 17;
13325  // };
13326 
13327  // C++ [class.mem]p4:
13328  // A member-declarator can contain a constant-initializer only
13329  // if it declares a static member (9.4) of const integral or
13330  // const enumeration type, see 9.4.2.
13331  //
13332  // C++11 [class.static.data]p3:
13333  // If a non-volatile non-inline const static data member is of integral
13334  // or enumeration type, its declaration in the class definition can
13335  // specify a brace-or-equal-initializer in which every initializer-clause
13336  // that is an assignment-expression is a constant expression. A static
13337  // data member of literal type can be declared in the class definition
13338  // with the constexpr specifier; if so, its declaration shall specify a
13339  // brace-or-equal-initializer in which every initializer-clause that is
13340  // an assignment-expression is a constant expression.
13341 
13342  // Do nothing on dependent types.
13343  if (DclT->isDependentType()) {
13344 
13345  // Allow any 'static constexpr' members, whether or not they are of literal
13346  // type. We separately check that every constexpr variable is of literal
13347  // type.
13348  } else if (VDecl->isConstexpr()) {
13349 
13350  // Require constness.
13351  } else if (!DclT.isConstQualified()) {
13352  Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13353  << Init->getSourceRange();
13354  VDecl->setInvalidDecl();
13355 
13356  // We allow integer constant expressions in all cases.
13357  } else if (DclT->isIntegralOrEnumerationType()) {
13358  // Check whether the expression is a constant expression.
13359  SourceLocation Loc;
13360  if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
13361  // In C++11, a non-constexpr const static data member with an
13362  // in-class initializer cannot be volatile.
13363  Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13364  else if (Init->isValueDependent())
13365  ; // Nothing to check.
13366  else if (Init->isIntegerConstantExpr(Context, &Loc))
13367  ; // Ok, it's an ICE!
13368  else if (Init->getType()->isScopedEnumeralType() &&
13369  Init->isCXX11ConstantExpr(Context))
13370  ; // Ok, it is a scoped-enum constant expression.
13371  else if (Init->isEvaluatable(Context)) {
13372  // If we can constant fold the initializer through heroics, accept it,
13373  // but report this as a use of an extension for -pedantic.
13374  Diag(Loc, diag::ext_in_class_initializer_non_constant)
13375  << Init->getSourceRange();
13376  } else {
13377  // Otherwise, this is some crazy unknown case. Report the issue at the
13378  // location provided by the isIntegerConstantExpr failed check.
13379  Diag(Loc, diag::err_in_class_initializer_non_constant)
13380  << Init->getSourceRange();
13381  VDecl->setInvalidDecl();
13382  }
13383 
13384  // We allow foldable floating-point constants as an extension.
13385  } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13386  // In C++98, this is a GNU extension. In C++11, it is not, but we support
13387  // it anyway and provide a fixit to add the 'constexpr'.
13388  if (getLangOpts().CPlusPlus11) {
13389  Diag(VDecl->getLocation(),
13390  diag::ext_in_class_initializer_float_type_cxx11)
13391  << DclT << Init->getSourceRange();
13392  Diag(VDecl->getBeginLoc(),
13393  diag::note_in_class_initializer_float_type_cxx11)
13394  << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13395  } else {
13396  Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13397  << DclT << Init->getSourceRange();
13398 
13399  if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13400  Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13401  << Init->getSourceRange();
13402  VDecl->setInvalidDecl();
13403  }
13404  }
13405 
13406  // Suggest adding 'constexpr' in C++11 for literal types.
13407  } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13408  Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13409  << DclT << Init->getSourceRange()
13410  << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13411  VDecl->setConstexpr(true);
13412 
13413  } else {
13414  Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13415  << DclT << Init->getSourceRange();
13416  VDecl->setInvalidDecl();
13417  }
13418  } else if (VDecl->isFileVarDecl()) {
13419  // In C, extern is typically used to avoid tentative definitions when
13420  // declaring variables in headers, but adding an intializer makes it a
13421  // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13422  // In C++, extern is often used to give implictly static const variables
13423  // external linkage, so don't warn in that case. If selectany is present,
13424  // this might be header code intended for C and C++ inclusion, so apply the
13425  // C++ rules.
13426  if (VDecl->getStorageClass() == SC_Extern &&
13427  ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13428  !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
13429  !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13431  Diag(VDecl->getLocation(), diag::warn_extern_init);
13432 
13433  // In Microsoft C++ mode, a const variable defined in namespace scope has
13434  // external linkage by default if the variable is declared with
13435  // __declspec(dllexport).
13436  if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13437  getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
13438  VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13439  VDecl->setStorageClass(SC_Extern);
13440 
13441  // C99 6.7.8p4. All file scoped initializers need to be constant.
13442  if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
13443  CheckForConstantInitializer(Init, DclT);
13444  }
13445 
13446  QualType InitType = Init->getType();
13447  if (!InitType.isNull() &&
13450  checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
13451 
13452  // We will represent direct-initialization similarly to copy-initialization:
13453  // int x(1); -as-> int x = 1;
13454  // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13455  //
13456  // Clients that want to distinguish between the two forms, can check for
13457  // direct initializer using VarDecl::getInitStyle().
13458  // A major benefit is that clients that don't particularly care about which
13459  // exactly form was it (like the CodeGen) can handle both cases without
13460  // special case code.
13461 
13462  // C++ 8.5p11:
13463  // The form of initialization (using parentheses or '=') is generally
13464  // insignificant, but does matter when the entity being initialized has a
13465  // class type.
13466  if (CXXDirectInit) {
13467  assert(DirectInit && "Call-style initializer must be direct init.");
13468  VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13469  : VarDecl::CallInit);
13470  } else if (DirectInit) {
13471  // This must be list-initialization. No other way is direct-initialization.
13473  }
13474 
13475  if (LangOpts.OpenMP &&
13476  (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
13477  VDecl->isFileVarDecl())
13478  DeclsToCheckForDeferredDiags.insert(VDecl);
13479  CheckCompleteVariableDeclaration(VDecl);
13480 }
13481 
13482 /// ActOnInitializerError - Given that there was an error parsing an
13483 /// initializer for the given declaration, try to at least re-establish
13484 /// invariants such as whether a variable's type is either dependent or
13485 /// complete.
13487  // Our main concern here is re-establishing invariants like "a
13488  // variable's type is either dependent or complete".
13489  if (!D || D->isInvalidDecl()) return;
13490 
13491  VarDecl *VD = dyn_cast<VarDecl>(D);
13492  if (!VD) return;
13493 
13494  // Bindings are not usable if we can't make sense of the initializer.
13495  if (auto *DD = dyn_cast<DecompositionDecl>(D))
13496  for (auto *BD : DD->bindings())
13497  BD->setInvalidDecl();
13498 
13499  // Auto types are meaningless if we can't make sense of the initializer.
13500  if (VD->getType()->isUndeducedType()) {
13501  D->setInvalidDecl();
13502  return;
13503  }
13504 
13505  QualType Ty = VD->getType();
13506  if (Ty->isDependentType()) return;
13507 
13508  // Require a complete type.
13509  if (RequireCompleteType(VD->getLocation(),
13510  Context.getBaseElementType(Ty),
13511  diag::err_typecheck_decl_incomplete_type)) {
13512  VD->setInvalidDecl();
13513  return;
13514  }
13515 
13516  // Require a non-abstract type.
13517  if (RequireNonAbstractType(VD->getLocation(), Ty,
13518  diag::err_abstract_type_in_decl,
13519  AbstractVariableType)) {
13520  VD->setInvalidDecl();
13521  return;
13522  }
13523 
13524  // Don't bother complaining about constructors or destructors,
13525  // though.
13526 }
13527 
13529  // If there is no declaration, there was an error parsing it. Just ignore it.
13530  if (!RealDecl)
13531  return;
13532 
13533  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13534  QualType Type = Var->getType();
13535 
13536  // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13537  if (isa<DecompositionDecl>(RealDecl)) {
13538  Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13539  Var->setInvalidDecl();
13540  return;
13541  }
13542 
13543  if (Type->isUndeducedType() &&
13544  DeduceVariableDeclarationType(Var, false, nullptr))
13545  return;
13546 
13547  // C++11 [class.static.data]p3: A static data member can be declared with
13548  // the constexpr specifier; if so, its declaration shall specify
13549  // a brace-or-equal-initializer.
13550  // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13551  // the definition of a variable [...] or the declaration of a static data
13552  // member.
13553  if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13554  !Var->isThisDeclarationADemotedDefinition()) {
13555  if (Var->isStaticDataMember()) {
13556  // C++1z removes the relevant rule; the in-class declaration is always
13557  // a definition there.
13558  if (!getLangOpts().CPlusPlus17 &&
13559  !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13560  Diag(Var->getLocation(),
13561  diag::err_constexpr_static_mem_var_requires_init)
13562  << Var;
13563  Var->setInvalidDecl();
13564  return;
13565  }
13566  } else {
13567  Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13568  Var->setInvalidDecl();
13569  return;
13570  }
13571  }
13572 
13573  // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13574  // be initialized.
13575  if (!Var->isInvalidDecl() &&
13576  Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13577  Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13578  bool HasConstExprDefaultConstructor = false;
13579  if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13580  for (auto *Ctor : RD->ctors()) {
13581  if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13582  Ctor->getMethodQualifiers().getAddressSpace() ==
13584  HasConstExprDefaultConstructor = true;
13585  }
13586  }
13587  }
13588  if (!HasConstExprDefaultConstructor) {
13589  Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13590  Var->setInvalidDecl();
13591  return;
13592  }
13593  }
13594 
13595  if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13596  if (Var->getStorageClass() == SC_Extern) {
13597  Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13598  << Var;
13599  Var->setInvalidDecl();
13600  return;
13601  }
13602  if (RequireCompleteType(Var->getLocation(), Var->getType(),
13603  diag::err_typecheck_decl_incomplete_type)) {
13604  Var->setInvalidDecl();
13605  return;
13606  }
13607  if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13608  if (!RD->hasTrivialDefaultConstructor()) {
13609  Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13610  Var->setInvalidDecl();
13611  return;
13612  }
13613  }
13614  // The declaration is unitialized, no need for further checks.
13615  return;
13616  }
13617 
13618  VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13619  if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13620  Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13621  checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13622  NTCUC_DefaultInitializedObject, NTCUK_Init);
13623 
13624 
13625  switch (DefKind) {
13626  case VarDecl::Definition:
13627  if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13628  break;
13629 
13630  // We have an out-of-line definition of a static data member
13631  // that has an in-class initializer, so we type-check this like
13632  // a declaration.
13633  //
13634  [[fallthrough]];
13635 
13637  // It's only a declaration.
13638 
13639  // Block scope. C99 6.7p7: If an identifier for an object is
13640  // declared with no linkage (C99 6.2.2p6), the type for the
13641  // object shall be complete.
13642  if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13643  !Var->hasLinkage() && !Var->isInvalidDecl() &&
13644  RequireCompleteType(Var->getLocation(), Type,
13645  diag::err_typecheck_decl_incomplete_type))
13646  Var->setInvalidDecl();
13647 
13648  // Make sure that the type is not abstract.
13649  if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13650  RequireNonAbstractType(Var->getLocation(), Type,
13651  diag::err_abstract_type_in_decl,
13652  AbstractVariableType))
13653  Var->setInvalidDecl();
13654  if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13655  Var->getStorageClass() == SC_PrivateExtern) {
13656  Diag(Var->getLocation(), diag::warn_private_extern);
13657  Diag(Var->getLocation(), diag::note_private_extern);
13658  }
13659 
13660  if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13661  !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
13662  ExternalDeclarations.push_back(Var);
13663 
13664  return;
13665 
13667  // File scope. C99 6.9.2p2: A declaration of an identifier for an
13668  // object that has file scope without an initializer, and without a
13669  // storage-class specifier or with the storage-class specifier "static",
13670  // constitutes a tentative definition. Note: A tentative definition with
13671  // external linkage is valid (C99 6.2.2p5).
13672  if (!Var->isInvalidDecl()) {
13673  if (const IncompleteArrayType *ArrayT
13674  = Context.getAsIncompleteArrayType(Type)) {
13675  if (RequireCompleteSizedType(
13676  Var->getLocation(), ArrayT->getElementType(),
13677  diag::err_array_incomplete_or_sizeless_type))
13678  Var->setInvalidDecl();
13679  } else if (Var->getStorageClass() == SC_Static) {
13680  // C99 6.9.2p3: If the declaration of an identifier for an object is
13681  // a tentative definition and has internal linkage (C99 6.2.2p3), the
13682  // declared type shall not be an incomplete type.
13683  // NOTE: code such as the following
13684  // static struct s;
13685  // struct s { int a; };
13686  // is accepted by gcc. Hence here we issue a warning instead of
13687  // an error and we do not invalidate the static declaration.
13688  // NOTE: to avoid multiple warnings, only check the first declaration.
13689  if (Var->isFirstDecl())
13690  RequireCompleteType(Var->getLocation(), Type,
13691  diag::ext_typecheck_decl_incomplete_type);
13692  }
13693  }
13694 
13695  // Record the tentative definition; we're done.
13696  if (!Var->isInvalidDecl())
13697  TentativeDefinitions.push_back(Var);
13698  return;
13699  }
13700 
13701  // Provide a specific diagnostic for uninitialized variable
13702  // definitions with incomplete array type.
13703  if (Type->isIncompleteArrayType()) {
13704  if (Var->isConstexpr())
13705  Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
13706  << Var;
13707  else
13708  Diag(Var->getLocation(),
13709  diag::err_typecheck_incomplete_array_needs_initializer);
13710  Var->setInvalidDecl();
13711  return;
13712  }
13713 
13714  // Provide a specific diagnostic for uninitialized variable
13715  // definitions with reference type.
13716  if (Type->isReferenceType()) {
13717  Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13718  << Var << SourceRange(Var->getLocation(), Var->getLocation());
13719  return;
13720  }
13721 
13722  // Do not attempt to type-check the default initializer for a
13723  // variable with dependent type.
13724  if (Type->isDependentType())
13725  return;
13726 
13727  if (Var->isInvalidDecl())
13728  return;
13729 
13730  if (!Var->hasAttr<AliasAttr>()) {
13731  if (RequireCompleteType(Var->getLocation(),
13732  Context.getBaseElementType(Type),
13733  diag::err_typecheck_decl_incomplete_type)) {
13734  Var->setInvalidDecl();
13735  return;
13736  }
13737  } else {
13738  return;
13739  }
13740 
13741  // The variable can not have an abstract class type.
13742  if (RequireNonAbstractType(Var->getLocation(), Type,
13743  diag::err_abstract_type_in_decl,
13744  AbstractVariableType)) {
13745  Var->setInvalidDecl();
13746  return;
13747  }
13748 
13749  // Check for jumps past the implicit initializer. C++0x
13750  // clarifies that this applies to a "variable with automatic
13751  // storage duration", not a "local variable".
13752  // C++11 [stmt.dcl]p3
13753  // A program that jumps from a point where a variable with automatic
13754  // storage duration is not in scope to a point where it is in scope is
13755  // ill-formed unless the variable has scalar type, class type with a
13756  // trivial default constructor and a trivial destructor, a cv-qualified
13757  // version of one of these types, or an array of one of the preceding
13758  // types and is declared without an initializer.
13759  if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13760  if (const RecordType *Record
13761  = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13762  CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13763  // Mark the function (if we're in one) for further checking even if the
13764  // looser rules of C++11 do not require such checks, so that we can
13765  // diagnose incompatibilities with C++98.
13766  if (!CXXRecord->isPOD())
13767  setFunctionHasBranchProtectedScope();
13768  }
13769  }
13770  // In OpenCL, we can't initialize objects in the __local address space,
13771  // even implicitly, so don't synthesize an implicit initializer.
13772  if (getLangOpts().OpenCL &&
13773  Var->getType().getAddressSpace() == LangAS::opencl_local)
13774  return;
13775  // C++03 [dcl.init]p9:
13776  // If no initializer is specified for an object, and the
13777  // object is of (possibly cv-qualified) non-POD class type (or
13778  // array thereof), the object shall be default-initialized; if
13779  // the object is of const-qualified type, the underlying class
13780  // type shall have a user-declared default
13781  // constructor. Otherwise, if no initializer is specified for
13782  // a non- static object, the object and its subobjects, if
13783  // any, have an indeterminate initial value); if the object
13784  // or any of its subobjects are of const-qualified type, the
13785  // program is ill-formed.
13786  // C++0x [dcl.init]p11:
13787  // If no initializer is specified for an object, the object is
13788  // default-initialized; [...].
13791  = InitializationKind::CreateDefault(Var->getLocation());
13792 
13793  InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
13794  ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt);
13795 
13796  if (Init.get()) {
13797  Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13798  // This is important for template substitution.
13799  Var->setInitStyle(VarDecl::CallInit);
13800  } else if (Init.isInvalid()) {
13801  // If default-init fails, attach a recovery-expr initializer to track
13802  // that initialization was attempted and failed.
13803  auto RecoveryExpr =
13804  CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13805  if (RecoveryExpr.get())
13806  Var->setInit(RecoveryExpr.get());
13807  }
13808 
13809  CheckCompleteVariableDeclaration(Var);
13810  }
13811 }
13812 
13814  // If there is no declaration, there was an error parsing it. Ignore it.
13815  if (!D)
13816  return;
13817 
13818  VarDecl *VD = dyn_cast<VarDecl>(D);
13819  if (!VD) {
13820  Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13821  D->setInvalidDecl();
13822  return;
13823  }
13824 
13825  VD->setCXXForRangeDecl(true);
13826 
13827  // for-range-declaration cannot be given a storage class specifier.
13828  int Error = -1;
13829  switch (VD->getStorageClass()) {
13830  case SC_None:
13831  break;
13832  case SC_Extern:
13833  Error = 0;
13834  break;
13835  case SC_Static:
13836  Error = 1;
13837  break;
13838  case SC_PrivateExtern:
13839  Error = 2;
13840  break;
13841  case SC_Auto:
13842  Error = 3;
13843  break;
13844  case SC_Register:
13845  Error = 4;
13846  break;
13847  }
13848 
13849  // for-range-declaration cannot be given a storage class specifier con't.
13850  switch (VD->getTSCSpec()) {
13851  case TSCS_thread_local:
13852  Error = 6;
13853  break;
13854  case TSCS___thread:
13855  case TSCS__Thread_local:
13856  case TSCS_unspecified:
13857  break;
13858  }
13859 
13860  if (Error != -1) {
13861  Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13862  << VD << Error;
13863  D->setInvalidDecl();
13864  }
13865 }
13866 
13868  IdentifierInfo *Ident,
13869  ParsedAttributes &Attrs) {
13870  // C++1y [stmt.iter]p1:
13871  // A range-based for statement of the form
13872  // for ( for-range-identifier : for-range-initializer ) statement
13873  // is equivalent to
13874  // for ( auto&& for-range-identifier : for-range-initializer ) statement
13875  DeclSpec DS(Attrs.getPool().getFactory());
13876 
13877  const char *PrevSpec;
13878  unsigned DiagID;
13879  DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13880  getPrintingPolicy());
13881 
13883  D.SetIdentifier(Ident, IdentLoc);
13884  D.takeAttributes(Attrs);
13885 
13886  D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13887  IdentLoc);
13888  Decl *Var = ActOnDeclarator(S, D);
13889  cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13890  FinalizeDeclaration(Var);
13891  return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13892  Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
13893  : IdentLoc);
13894 }
13895 
13897  if (var->isInvalidDecl()) return;
13898 
13899  MaybeAddCUDAConstantAttr(var);
13900 
13901  if (getLangOpts().OpenCL) {
13902  // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13903  // initialiser
13904  if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13905  !var->hasInit()) {
13906  Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13907  << 1 /*Init*/;
13908  var->setInvalidDecl();
13909  return;
13910  }
13911  }
13912 
13913  // In Objective-C, don't allow jumps past the implicit initialization of a
13914  // local retaining variable.
13915  if (getLangOpts().ObjC &&
13916  var->hasLocalStorage()) {
13917  switch (var->getType().getObjCLifetime()) {
13918  case Qualifiers::OCL_None:
13921  break;
13922 
13923  case Qualifiers::OCL_Weak:
13925  setFunctionHasBranchProtectedScope();
13926  break;
13927  }
13928  }
13929 
13930  if (var->hasLocalStorage() &&
13931  var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13932  setFunctionHasBranchProtectedScope();
13933 
13934  // Warn about externally-visible variables being defined without a
13935  // prior declaration. We only want to do this for global
13936  // declarations, but we also specifically need to avoid doing it for
13937  // class members because the linkage of an anonymous class can
13938  // change if it's later given a typedef name.
13939  if (var->isThisDeclarationADefinition() &&
13940  var->getDeclContext()->getRedeclContext()->isFileContext() &&
13941  var->isExternallyVisible() && var->hasLinkage() &&
13942  !var->isInline() && !var->getDescribedVarTemplate() &&
13943  !isa<VarTemplatePartialSpecializationDecl>(var) &&
13944  !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13945  !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13946  var->getLocation())) {
13947  // Find a previous declaration that's not a definition.
13948  VarDecl *prev = var->getPreviousDecl();
13949  while (prev && prev->isThisDeclarationADefinition())
13950  prev = prev->getPreviousDecl();
13951 
13952  if (!prev) {
13953  Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13954  Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13955  << /* variable */ 0;
13956  }
13957  }
13958 
13959  // Cache the result of checking for constant initialization.
13960  std::optional<bool> CacheHasConstInit;
13961  const Expr *CacheCulprit = nullptr;
13962  auto checkConstInit = [&]() mutable {
13963  if (!CacheHasConstInit)
13964  CacheHasConstInit = var->getInit()->isConstantInitializer(
13965  Context, var->getType()->isReferenceType(), &CacheCulprit);
13966  return *CacheHasConstInit;
13967  };
13968 
13969  if (var->getTLSKind() == VarDecl::TLS_Static) {
13970  if (var->getType().isDestructedType()) {
13971  // GNU C++98 edits for __thread, [basic.start.term]p3:
13972  // The type of an object with thread storage duration shall not
13973  // have a non-trivial destructor.
13974  Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13975  if (getLangOpts().CPlusPlus11)
13976  Diag(var->getLocation(), diag::note_use_thread_local);
13977  } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13978  if (!checkConstInit()) {
13979  // GNU C++98 edits for __thread, [basic.start.init]p4:
13980  // An object of thread storage duration shall not require dynamic
13981  // initialization.
13982  // FIXME: Need strict checking here.
13983  Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13984  << CacheCulprit->getSourceRange();
13985  if (getLangOpts().CPlusPlus11)
13986  Diag(var->getLocation(), diag::note_use_thread_local);
13987  }
13988  }
13989  }
13990 
13991 
13992  if (!var->getType()->isStructureType() && var->hasInit() &&
13993  isa<InitListExpr>(var->getInit())) {
13994  const auto *ILE = cast<InitListExpr>(var->getInit());
13995  unsigned NumInits = ILE->getNumInits();
13996  if (NumInits > 2)
13997  for (unsigned I = 0; I < NumInits; ++I) {
13998  const auto *Init = ILE->getInit(I);
13999  if (!Init)
14000  break;
14001  const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14002  if (!SL)
14003  break;
14004 
14005  unsigned NumConcat = SL->getNumConcatenated();
14006  // Diagnose missing comma in string array initialization.
14007  // Do not warn when all the elements in the initializer are concatenated
14008  // together. Do not warn for macros too.
14009  if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14010  bool OnlyOneMissingComma = true;
14011  for (unsigned J = I + 1; J < NumInits; ++J) {
14012  const auto *Init = ILE->getInit(J);
14013  if (!Init)
14014  break;
14015  const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14016  if (!SLJ || SLJ->getNumConcatenated() > 1) {
14017  OnlyOneMissingComma = false;
14018  break;
14019  }
14020  }
14021 
14022  if (OnlyOneMissingComma) {
14024  for (unsigned i = 0; i < NumConcat - 1; ++i)
14025  Hints.push_back(FixItHint::CreateInsertion(
14026  PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14027 
14028  Diag(SL->getStrTokenLoc(1),
14029  diag::warn_concatenated_literal_array_init)
14030  << Hints;
14031  Diag(SL->getBeginLoc(),
14032  diag::note_concatenated_string_literal_silence);
14033  }
14034  // In any case, stop now.
14035  break;
14036  }
14037  }
14038  }
14039 
14040 
14041  QualType type = var->getType();
14042 
14043  if (var->hasAttr<BlocksAttr>())
14044  getCurFunction()->addByrefBlockVar(var);
14045 
14046  Expr *Init = var->getInit();
14047  bool GlobalStorage = var->hasGlobalStorage();
14048  bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14049  QualType baseType = Context.getBaseElementType(type);
14050  bool HasConstInit = true;
14051 
14052  // Check whether the initializer is sufficiently constant.
14053  if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
14054  !Init->isValueDependent() &&
14055  (GlobalStorage || var->isConstexpr() ||
14056  var->mightBeUsableInConstantExpressions(Context))) {
14057  // If this variable might have a constant initializer or might be usable in
14058  // constant expressions, check whether or not it actually is now. We can't
14059  // do this lazily, because the result might depend on things that change
14060  // later, such as which constexpr functions happen to be defined.
14062  if (!getLangOpts().CPlusPlus11) {
14063  // Prior to C++11, in contexts where a constant initializer is required,
14064  // the set of valid constant initializers is described by syntactic rules
14065  // in [expr.const]p2-6.
14066  // FIXME: Stricter checking for these rules would be useful for constinit /
14067  // -Wglobal-constructors.
14068  HasConstInit = checkConstInit();
14069 
14070  // Compute and cache the constant value, and remember that we have a
14071  // constant initializer.
14072  if (HasConstInit) {
14073  (void)var->checkForConstantInitialization(Notes);
14074  Notes.clear();
14075  } else if (CacheCulprit) {
14076  Notes.emplace_back(CacheCulprit->getExprLoc(),
14077  PDiag(diag::note_invalid_subexpr_in_const_expr));
14078  Notes.back().second << CacheCulprit->getSourceRange();
14079  }
14080  } else {
14081  // Evaluate the initializer to see if it's a constant initializer.
14082  HasConstInit = var->checkForConstantInitialization(Notes);
14083  }
14084 
14085  if (HasConstInit) {
14086  // FIXME: Consider replacing the initializer with a ConstantExpr.
14087  } else if (var->isConstexpr()) {
14088  SourceLocation DiagLoc = var->getLocation();
14089  // If the note doesn't add any useful information other than a source
14090  // location, fold it into the primary diagnostic.
14091  if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14092  diag::note_invalid_subexpr_in_const_expr) {
14093  DiagLoc = Notes[0].first;
14094  Notes.clear();
14095  }
14096  Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14097  << var << Init->getSourceRange();
14098  for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14099  Diag(Notes[I].first, Notes[I].second);
14100  } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14101  auto *Attr = var->getAttr<ConstInitAttr>();
14102  Diag(var->getLocation(), diag::err_require_constant_init_failed)
14103  << Init->getSourceRange();
14104  Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14105  << Attr->getRange() << Attr->isConstinit();
14106  for (auto &it : Notes)
14107  Diag(it.first, it.second);
14108  } else if (IsGlobal &&
14109  !getDiagnostics().isIgnored(diag::warn_global_constructor,
14110  var->getLocation())) {
14111  // Warn about globals which don't have a constant initializer. Don't
14112  // warn about globals with a non-trivial destructor because we already
14113  // warned about them.
14114  CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14115  if (!(RD && !RD->hasTrivialDestructor())) {
14116  // checkConstInit() here permits trivial default initialization even in
14117  // C++11 onwards, where such an initializer is not a constant initializer
14118  // but nonetheless doesn't require a global constructor.
14119  if (!checkConstInit())
14120  Diag(var->getLocation(), diag::warn_global_constructor)
14121  << Init->getSourceRange();
14122  }
14123  }
14124  }
14125 
14126  // Apply section attributes and pragmas to global variables.
14127  if (GlobalStorage && var->isThisDeclarationADefinition() &&
14128  !inTemplateInstantiation()) {
14129  PragmaStack<StringLiteral *> *Stack = nullptr;
14130  int SectionFlags = ASTContext::PSF_Read;
14131  if (var->getType().isConstQualified()) {
14132  if (HasConstInit)
14133  Stack = &ConstSegStack;
14134  else {
14135  Stack = &BSSSegStack;
14136  SectionFlags |= ASTContext::PSF_Write;
14137  }
14138  } else if (var->hasInit() && HasConstInit) {
14139  Stack = &DataSegStack;
14140  SectionFlags |= ASTContext::PSF_Write;
14141  } else {
14142  Stack = &BSSSegStack;
14143  SectionFlags |= ASTContext::PSF_Write;
14144  }
14145  if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14146  if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14147  SectionFlags |= ASTContext::PSF_Implicit;
14148  UnifySection(SA->getName(), SectionFlags, var);
14149  } else if (Stack->CurrentValue) {
14150  SectionFlags |= ASTContext::PSF_Implicit;
14151  auto SectionName = Stack->CurrentValue->getString();
14152  var->addAttr(SectionAttr::CreateImplicit(
14153  Context, SectionName, Stack->CurrentPragmaLocation,
14154  AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
14155  if (UnifySection(SectionName, SectionFlags, var))
14156  var->dropAttr<SectionAttr>();
14157  }
14158 
14159  // Apply the init_seg attribute if this has an initializer. If the
14160  // initializer turns out to not be dynamic, we'll end up ignoring this
14161  // attribute.
14162  if (CurInitSeg && var->getInit())
14163  var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14164  CurInitSegLoc,
14166  }
14167 
14168  // All the following checks are C++ only.
14169  if (!getLangOpts().CPlusPlus) {
14170  // If this variable must be emitted, add it as an initializer for the
14171  // current module.
14172  if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14173  Context.addModuleInitializer(ModuleScopes.back().Module, var);
14174  return;
14175  }
14176 
14177  // Require the destructor.
14178  if (!type->isDependentType())
14179  if (const RecordType *recordType = baseType->getAs<RecordType>())
14180  FinalizeVarWithDestructor(var, recordType);
14181 
14182  // If this variable must be emitted, add it as an initializer for the current
14183  // module.
14184  if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14185  Context.addModuleInitializer(ModuleScopes.back().Module, var);
14186 
14187  // Build the bindings if this is a structured binding declaration.
14188  if (auto *DD = dyn_cast<DecompositionDecl>(var))
14189  CheckCompleteDecompositionDeclaration(DD);
14190 }
14191 
14192 /// Check if VD needs to be dllexport/dllimport due to being in a
14193 /// dllexport/import function.
14195  assert(VD->isStaticLocal());
14196 
14197  auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14198 
14199  // Find outermost function when VD is in lambda function.
14200  while (FD && !getDLLAttr(FD) &&
14201  !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14202  !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14203  FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14204  }
14205 
14206  if (!FD)
14207  return;
14208 
14209  // Static locals inherit dll attributes from their function.
14210  if (Attr *A = getDLLAttr(FD)) {
14211  auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14212  NewAttr->setInherited(true);
14213  VD->addAttr(NewAttr);
14214  } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14215  auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14216  NewAttr->setInherited(true);
14217  VD->addAttr(NewAttr);
14218 
14219  // Export this function to enforce exporting this static variable even
14220  // if it is not used in this compilation unit.
14221  if (!FD->hasAttr<DLLExportAttr>())
14222  FD->addAttr(NewAttr);
14223 
14224  } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14225  auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14226  NewAttr->setInherited(true);
14227  VD->addAttr(NewAttr);
14228  }
14229 }
14230 
14232  assert(VD->getTLSKind());
14233 
14234  // Perform TLS alignment check here after attributes attached to the variable
14235  // which may affect the alignment have been processed. Only perform the check
14236  // if the target has a maximum TLS alignment (zero means no constraints).
14237  if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14238  // Protect the check so that it's not performed on dependent types and
14239  // dependent alignments (we can't determine the alignment in that case).
14240  if (!VD->hasDependentAlignment()) {
14241  CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14242  if (Context.getDeclAlign(VD) > MaxAlignChars) {
14243  Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14244  << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
14245  << (unsigned)MaxAlignChars.getQuantity();
14246  }
14247  }
14248  }
14249 }
14250 
14251 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
14252 /// any semantic actions necessary after any initializer has been attached.
14254  // Note that we are no longer parsing the initializer for this declaration.
14255  ParsingInitForAutoVars.erase(ThisDecl);
14256 
14257  VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14258  if (!VD)
14259  return;
14260 
14261  // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14262  if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
14263  !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14264  if (PragmaClangBSSSection.Valid)
14265  VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14266  Context, PragmaClangBSSSection.SectionName,
14267  PragmaClangBSSSection.PragmaLocation,
14269  if (PragmaClangDataSection.Valid)
14270  VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14271  Context, PragmaClangDataSection.SectionName,
14272  PragmaClangDataSection.PragmaLocation,
14274  if (PragmaClangRodataSection.Valid)
14275  VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14276  Context, PragmaClangRodataSection.SectionName,
14277  PragmaClangRodataSection.PragmaLocation,
14279  if (PragmaClangRelroSection.Valid)
14280  VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14281  Context, PragmaClangRelroSection.SectionName,
14282  PragmaClangRelroSection.PragmaLocation,
14284  }
14285 
14286  if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14287  for (auto *BD : DD->bindings()) {
14288  FinalizeDeclaration(BD);
14289  }
14290  }
14291 
14292  checkAttributesAfterMerging(*this, *VD);
14293 
14294  if (VD->isStaticLocal())
14295  CheckStaticLocalForDllExport(VD);
14296 
14297  if (VD->getTLSKind())
14298  CheckThreadLocalForLargeAlignment(VD);
14299 
14300  // Perform check for initializers of device-side global variables.
14301  // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14302  // 7.5). We must also apply the same checks to all __shared__
14303  // variables whether they are local or not. CUDA also allows
14304  // constant initializers for __constant__ and __device__ variables.
14305  if (getLangOpts().CUDA)
14306  checkAllowedCUDAInitializer(VD);
14307 
14308  // Grab the dllimport or dllexport attribute off of the VarDecl.
14309  const InheritableAttr *DLLAttr = getDLLAttr(VD);
14310 
14311  // Imported static data members cannot be defined out-of-line.
14312  if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14313  if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14315  // We allow definitions of dllimport class template static data members
14316  // with a warning.
14317  CXXRecordDecl *Context =
14318  cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14319  bool IsClassTemplateMember =
14320  isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14321  Context->getDescribedClassTemplate();
14322 
14323  Diag(VD->getLocation(),
14324  IsClassTemplateMember
14325  ? diag::warn_attribute_dllimport_static_field_definition
14326  : diag::err_attribute_dllimport_static_field_definition);
14327  Diag(IA->getLocation(), diag::note_attribute);
14328  if (!IsClassTemplateMember)
14329  VD->setInvalidDecl();
14330  }
14331  }
14332 
14333  // dllimport/dllexport variables cannot be thread local, their TLS index
14334  // isn't exported with the variable.
14335  if (DLLAttr && VD->getTLSKind()) {
14336  auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14337  if (F && getDLLAttr(F)) {
14338  assert(VD->isStaticLocal());
14339  // But if this is a static local in a dlimport/dllexport function, the
14340  // function will never be inlined, which means the var would never be
14341  // imported, so having it marked import/export is safe.
14342  } else {
14343  Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14344  << DLLAttr;
14345  VD->setInvalidDecl();
14346  }
14347  }
14348 
14349  if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14350  if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14351  Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14352  << Attr;
14353  VD->dropAttr<UsedAttr>();
14354  }
14355  }
14356  if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14357  if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14358  Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14359  << Attr;
14360  VD->dropAttr<RetainAttr>();
14361  }
14362  }
14363 
14364  const DeclContext *DC = VD->getDeclContext();
14365  // If there's a #pragma GCC visibility in scope, and this isn't a class
14366  // member, set the visibility of this variable.
14367  if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
14368  AddPushedVisibilityAttribute(VD);
14369 
14370  // FIXME: Warn on unused var template partial specializations.
14371  if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14372  MarkUnusedFileScopedDecl(VD);
14373 
14374  // Now we have parsed the initializer and can update the table of magic
14375  // tag values.
14376  if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14378  return;
14379 
14380  for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14381  const Expr *MagicValueExpr = VD->getInit();
14382  if (!MagicValueExpr) {
14383  continue;
14384  }
14385  std::optional<llvm::APSInt> MagicValueInt;
14386  if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14387  Diag(I->getRange().getBegin(),
14388  diag::err_type_tag_for_datatype_not_ice)
14389  << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14390  continue;
14391  }
14392  if (MagicValueInt->getActiveBits() > 64) {
14393  Diag(I->getRange().getBegin(),
14394  diag::err_type_tag_for_datatype_too_large)
14395  << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14396  continue;
14397  }
14398  uint64_t MagicValue = MagicValueInt->getZExtValue();
14399  RegisterTypeTagForDatatype(I->getArgumentKind(),
14400  MagicValue,
14401  I->getMatchingCType(),
14402  I->getLayoutCompatible(),
14403  I->getMustBeNull());
14404  }
14405 }
14406 
14407 static bool hasDeducedAuto(DeclaratorDecl *DD) {
14408  auto *VD = dyn_cast<VarDecl>(DD);
14409  return VD && !VD->getType()->hasAutoForTrailingReturnType();
14410 }
14411 
14414  SmallVector<Decl*, 8> Decls;
14415 
14416  if (DS.isTypeSpecOwned())
14417  Decls.push_back(DS.getRepAsDecl());
14418 
14419  DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14420  DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14421  bool DiagnosedMultipleDecomps = false;
14422  DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14423  bool DiagnosedNonDeducedAuto = false;
14424 
14425  for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14426  if (Decl *D = Group[i]) {
14427  // For declarators, there are some additional syntactic-ish checks we need
14428  // to perform.
14429  if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14430  if (!FirstDeclaratorInGroup)
14431  FirstDeclaratorInGroup = DD;
14432  if (!FirstDecompDeclaratorInGroup)
14433  FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14434  if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14435  !hasDeducedAuto(DD))
14436  FirstNonDeducedAutoInGroup = DD;
14437 
14438  if (FirstDeclaratorInGroup != DD) {
14439  // A decomposition declaration cannot be combined with any other
14440  // declaration in the same group.
14441  if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14442  Diag(FirstDecompDeclaratorInGroup->getLocation(),
14443  diag::err_decomp_decl_not_alone)
14444  << FirstDeclaratorInGroup->getSourceRange()
14445  << DD->getSourceRange();
14446  DiagnosedMultipleDecomps = true;
14447  }
14448 
14449  // A declarator that uses 'auto' in any way other than to declare a
14450  // variable with a deduced type cannot be combined with any other
14451  // declarator in the same group.
14452  if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14453  Diag(FirstNonDeducedAutoInGroup->getLocation(),
14454  diag::err_auto_non_deduced_not_alone)
14455  << FirstNonDeducedAutoInGroup->getType()
14457  << FirstDeclaratorInGroup->getSourceRange()
14458  << DD->getSourceRange();
14459  DiagnosedNonDeducedAuto = true;
14460  }
14461  }
14462  }
14463 
14464  Decls.push_back(D);
14465  }
14466  }
14467 
14469  if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14470  handleTagNumbering(Tag, S);
14471  if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14472  getLangOpts().CPlusPlus)
14473  Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14474  }
14475  }
14476 
14477  return BuildDeclaratorGroup(Decls);
14478 }
14479 
14480 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
14481 /// group, performing any necessary semantic checking.
14484  // C++14 [dcl.spec.auto]p7: (DR1347)
14485  // If the type that replaces the placeholder type is not the same in each
14486  // deduction, the program is ill-formed.
14487  if (Group.size() > 1) {
14488  QualType Deduced;
14489  VarDecl *DeducedDecl = nullptr;
14490  for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14491  VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14492  if (!D || D->isInvalidDecl())
14493  break;
14495  if (!DT || DT->getDeducedType().isNull())
14496  continue;
14497  if (Deduced.isNull()) {
14498  Deduced = DT->getDeducedType();
14499  DeducedDecl = D;
14500  } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14501  auto *AT = dyn_cast<AutoType>(DT);
14502  auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14503  diag::err_auto_different_deductions)
14504  << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14505  << DeducedDecl->getDeclName() << DT->getDeducedType()
14506  << D->getDeclName();
14507  if (DeducedDecl->hasInit())
14508  Dia << DeducedDecl->getInit()->getSourceRange();
14509  if (D->getInit())
14510  Dia << D->getInit()->getSourceRange();
14511  D->setInvalidDecl();
14512  break;
14513  }
14514  }
14515  }
14516 
14517  ActOnDocumentableDecls(Group);
14518 
14519  return DeclGroupPtrTy::make(
14520  DeclGroupRef::Create(Context, Group.data(), Group.size()));
14521 }
14522 
14524  ActOnDocumentableDecls(D);
14525 }
14526 
14528  // Don't parse the comment if Doxygen diagnostics are ignored.
14529  if (Group.empty() || !Group[0])
14530  return;
14531 
14532  if (Diags.isIgnored(diag::warn_doc_param_not_found,
14533  Group[0]->getLocation()) &&
14534  Diags.isIgnored(diag::warn_unknown_comment_command_name,
14535  Group[0]->getLocation()))
14536  return;
14537 
14538  if (Group.size() >= 2) {
14539  // This is a decl group. Normally it will contain only declarations
14540  // produced from declarator list. But in case we have any definitions or
14541  // additional declaration references:
14542  // 'typedef struct S {} S;'
14543  // 'typedef struct S *S;'
14544  // 'struct S *pS;'
14545  // FinalizeDeclaratorGroup adds these as separate declarations.
14546  Decl *MaybeTagDecl = Group[0];
14547  if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14548  Group = Group.slice(1);
14549  }
14550  }
14551 
14552  // FIMXE: We assume every Decl in the group is in the same file.
14553  // This is false when preprocessor constructs the group from decls in
14554  // different files (e. g. macros or #include).
14555  Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14556 }
14557 
14558 /// Common checks for a parameter-declaration that should apply to both function
14559 /// parameters and non-type template parameters.
14561  // Check that there are no default arguments inside the type of this
14562  // parameter.
14563  if (getLangOpts().CPlusPlus)
14564  CheckExtraCXXDefaultArguments(D);
14565 
14566  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14567  if (D.getCXXScopeSpec().isSet()) {
14568  Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14569  << D.getCXXScopeSpec().getRange();
14570  }
14571 
14572  // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14573  // simple identifier except [...irrelevant cases...].
14574  switch (D.getName().getKind()) {
14576  break;
14577 
14585  Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14586  << GetNameForDeclarator(D).getName();
14587  break;
14588 
14591  // GetNameForDeclarator would not produce a useful name in this case.
14592  Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14593  break;
14594  }
14595 }
14596 
14597 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14598 /// to introduce parameters into function prototype scope.
14600  const DeclSpec &DS = D.getDeclSpec();
14601 
14602  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14603 
14604  // C++03 [dcl.stc]p2 also permits 'auto'.
14605  StorageClass SC = SC_None;
14607  SC = SC_Register;
14608  // In C++11, the 'register' storage class specifier is deprecated.
14609  // In C++17, it is not allowed, but we tolerate it as an extension.
14610  if (getLangOpts().CPlusPlus11) {
14612  getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14613  : diag::warn_deprecated_register)
14615  }
14616  } else if (getLangOpts().CPlusPlus &&
14618  SC = SC_Auto;
14619  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14621  diag::err_invalid_storage_class_in_func_decl);
14623  }
14624 
14625  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14626  Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14627  << DeclSpec::getSpecifierName(TSCS);
14628  if (DS.isInlineSpecified())
14629  Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14630  << getLangOpts().CPlusPlus17;
14631  if (DS.hasConstexprSpecifier())
14632  Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14633  << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14634 
14635  DiagnoseFunctionSpecifiers(DS);
14636 
14637  CheckFunctionOrTemplateParamDeclarator(S, D);
14638 
14639  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14640  QualType parmDeclType = TInfo->getType();
14641 
14642  // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14643  IdentifierInfo *II = D.getIdentifier();
14644  if (II) {
14645  LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14646  ForVisibleRedeclaration);
14647  LookupName(R, S);
14648  if (R.isSingleResult()) {
14649  NamedDecl *PrevDecl = R.getFoundDecl();
14650  if (PrevDecl->isTemplateParameter()) {
14651  // Maybe we will complain about the shadowed template parameter.
14652  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14653  // Just pretend that we didn't see the previous declaration.
14654  PrevDecl = nullptr;
14655  } else if (S->isDeclScope(PrevDecl)) {
14656  Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14657  Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14658 
14659  // Recover by removing the name
14660  II = nullptr;
14661  D.SetIdentifier(nullptr, D.getIdentifierLoc());
14662  D.setInvalidType(true);
14663  }
14664  }
14665  }
14666 
14667  // Temporarily put parameter variables in the translation unit, not
14668  // the enclosing context. This prevents them from accidentally
14669  // looking like class members in C++.
14670  ParmVarDecl *New =
14671  CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14672  D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14673 
14674  if (D.isInvalidType())
14675  New->setInvalidDecl();
14676 
14677  assert(S->isFunctionPrototypeScope());
14678  assert(S->getFunctionPrototypeDepth() >= 1);
14679  New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14680  S->getNextFunctionPrototypeIndex());
14681 
14682  // Add the parameter declaration into this scope.
14683  S->AddDecl(New);
14684  if (II)
14685  IdResolver.AddDecl(New);
14686 
14687  ProcessDeclAttributes(S, New, D);
14688 
14690  Diag(New->getLocation(), diag::err_module_private_local)
14691  << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14693 
14694  if (New->hasAttr<BlocksAttr>()) {
14695  Diag(New->getLocation(), diag::err_block_on_nonlocal);
14696  }
14697 
14698  if (getLangOpts().OpenCL)
14699  deduceOpenCLAddressSpace(New);
14700 
14701  return New;
14702 }
14703 
14704 /// Synthesizes a variable for a parameter arising from a
14705 /// typedef.
14707  SourceLocation Loc,
14708  QualType T) {
14709  /* FIXME: setting StartLoc == Loc.
14710  Would it be worth to modify callers so as to provide proper source
14711  location for the unnamed parameters, embedding the parameter's type? */
14712  ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14713  T, Context.getTrivialTypeSourceInfo(T, Loc),
14714  SC_None, nullptr);
14715  Param->setImplicit();
14716  return Param;
14717 }
14718 
14720  // Don't diagnose unused-parameter errors in template instantiations; we
14721  // will already have done so in the template itself.
14722  if (inTemplateInstantiation())
14723  return;
14724 
14725  for (const ParmVarDecl *Parameter : Parameters) {
14726  if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14727  !Parameter->hasAttr<UnusedAttr>()) {
14728  Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14729  << Parameter->getDeclName();
14730  }
14731  }
14732 }
14733 
14735  ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14736  if (LangOpts.NumLargeByValueCopy == 0) // No check.
14737  return;
14738 
14739  // Warn if the return value is pass-by-value and larger than the specified
14740  // threshold.
14741  if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14742  unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14743  if (Size > LangOpts.NumLargeByValueCopy)
14744  Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14745  }
14746 
14747  // Warn if any parameter is pass-by-value and larger than the specified
14748  // threshold.
14749  for (const ParmVarDecl *Parameter : Parameters) {
14750  QualType T = Parameter->getType();
14751  if (T->isDependentType() || !T.isPODType(Context))
14752  continue;
14753  unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14754  if (Size > LangOpts.NumLargeByValueCopy)
14755  Diag(Parameter->getLocation(), diag::warn_parameter_size)
14756  << Parameter << Size;
14757  }
14758 }
14759 
14761  SourceLocation NameLoc, IdentifierInfo *Name,
14762  QualType T, TypeSourceInfo *TSInfo,
14763  StorageClass SC) {
14764  // In ARC, infer a lifetime qualifier for appropriate parameter types.
14765  if (getLangOpts().ObjCAutoRefCount &&
14767  T->isObjCLifetimeType()) {
14768 
14769  Qualifiers::ObjCLifetime lifetime;
14770 
14771  // Special cases for arrays:
14772  // - if it's const, use __unsafe_unretained
14773  // - otherwise, it's an error
14774  if (T->isArrayType()) {
14775  if (!T.isConstQualified()) {
14779  NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14780  else
14781  Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14782  << TSInfo->getTypeLoc().getSourceRange();
14783  }
14784  lifetime = Qualifiers::OCL_ExplicitNone;
14785  } else {
14786  lifetime = T->getObjCARCImplicitLifetime();
14787  }
14788  T = Context.getLifetimeQualifiedType(T, lifetime);
14789  }
14790 
14791  ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14792  Context.getAdjustedParameterType(T),
14793  TSInfo, SC, nullptr);
14794 
14795  // Make a note if we created a new pack in the scope of a lambda, so that
14796  // we know that references to that pack must also be expanded within the
14797  // lambda scope.
14798  if (New->isParameterPack())
14799  if (auto *LSI = getEnclosingLambda())
14800  LSI->LocalPacks.push_back(New);
14801 
14804  checkNonTrivialCUnion(New->getType(), New->getLocation(),
14805  NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14806 
14807  // Parameters can not be abstract class types.
14808  // For record types, this is done by the AbstractClassUsageDiagnoser once
14809  // the class has been completely parsed.
14810  if (!CurContext->isRecord() &&
14811  RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14812  AbstractParamType))
14813  New->setInvalidDecl();
14814 
14815  // Parameter declarators cannot be interface types. All ObjC objects are
14816  // passed by reference.
14817  if (T->isObjCObjectType()) {
14818  SourceLocation TypeEndLoc =
14819  getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14820  Diag(NameLoc,
14821  diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14822  << FixItHint::CreateInsertion(TypeEndLoc, "*");
14823  T = Context.getObjCObjectPointerType(T);
14824  New->setType(T);
14825  }
14826 
14827  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14828  // duration shall not be qualified by an address-space qualifier."
14829  // Since all parameters have automatic store duration, they can not have
14830  // an address space.
14831  if (T.getAddressSpace() != LangAS::Default &&
14832  // OpenCL allows function arguments declared to be an array of a type
14833  // to be qualified with an address space.
14834  !(getLangOpts().OpenCL &&
14836  Diag(NameLoc, diag::err_arg_with_address_space);
14837  New->setInvalidDecl();
14838  }
14839 
14840  // PPC MMA non-pointer types are not allowed as function argument types.
14841  if (Context.getTargetInfo().getTriple().isPPC64() &&
14842  CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14843  New->setInvalidDecl();
14844  }
14845 
14846  return New;
14847 }
14848 
14850  SourceLocation LocAfterDecls) {
14852 
14853  // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
14854  // in the declaration list shall have at least one declarator, those
14855  // declarators shall only declare identifiers from the identifier list, and
14856  // every identifier in the identifier list shall be declared.
14857  //
14858  // C89 3.7.1p5 "If a declarator includes an identifier list, only the
14859  // identifiers it names shall be declared in the declaration list."
14860  //
14861  // This is why we only diagnose in C99 and later. Note, the other conditions
14862  // listed are checked elsewhere.
14863  if (!FTI.hasPrototype) {
14864  for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14865  --i;
14866  if (FTI.Params[i].Param == nullptr) {
14867  if (getLangOpts().C99) {
14868  SmallString<256> Code;
14869  llvm::raw_svector_ostream(Code)
14870  << " int " << FTI.Params[i].Ident->getName() << ";\n";
14871  Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14872  << FTI.Params[i].Ident
14873  << FixItHint::CreateInsertion(LocAfterDecls, Code);
14874  }
14875 
14876  // Implicitly declare the argument as type 'int' for lack of a better
14877  // type.
14878  AttributeFactory attrs;
14879  DeclSpec DS(attrs);
14880  const char* PrevSpec; // unused
14881  unsigned DiagID; // unused
14882  DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14883  DiagID, Context.getPrintingPolicy());
14884  // Use the identifier location for the type source range.
14885  DS.SetRangeStart(FTI.Params[i].IdentLoc);
14886  DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14889  ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14890  FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14891  }
14892  }
14893  }
14894 }
14895 
14896 Decl *
14898  MultiTemplateParamsArg TemplateParameterLists,
14899  SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
14900  assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14901  assert(D.isFunctionDeclarator() && "Not a function declarator!");
14902  Scope *ParentScope = FnBodyScope->getParent();
14903 
14904  // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14905  // we define a non-templated function definition, we will create a declaration
14906  // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14907  // The base function declaration will have the equivalent of an `omp declare
14908  // variant` annotation which specifies the mangled definition as a
14909  // specialization function under the OpenMP context defined as part of the
14910  // `omp begin declare variant`.
14912  if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14913  ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14914  ParentScope, D, TemplateParameterLists, Bases);
14915 
14917  Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14918  Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
14919 
14920  if (!Bases.empty())
14921  ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14922 
14923  return Dcl;
14924 }
14925 
14927  Consumer.HandleInlineFunctionDefinition(D);
14928 }
14929 
14930 static bool FindPossiblePrototype(const FunctionDecl *FD,
14931  const FunctionDecl *&PossiblePrototype) {
14932  for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
14933  Prev = Prev->getPreviousDecl()) {
14934  // Ignore any declarations that occur in function or method
14935  // scope, because they aren't visible from the header.
14936  if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14937  continue;
14938 
14939  PossiblePrototype = Prev;
14940  return Prev->getType()->isFunctionProtoType();
14941  }
14942  return false;
14943 }
14944 
14945 static bool
14947  const FunctionDecl *&PossiblePrototype) {
14948  // Don't warn about invalid declarations.
14949  if (FD->isInvalidDecl())
14950  return false;
14951 
14952  // Or declarations that aren't global.
14953  if (!FD->isGlobal())
14954  return false;
14955 
14956  // Don't warn about C++ member functions.
14957  if (isa<CXXMethodDecl>(FD))
14958  return false;
14959 
14960  // Don't warn about 'main'.
14961  if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14962  if (IdentifierInfo *II = FD->getIdentifier())
14963  if (II->isStr("main") || II->isStr("efi_main"))
14964  return false;
14965 
14966  // Don't warn about inline functions.
14967  if (FD->isInlined())
14968  return false;
14969 
14970  // Don't warn about function templates.
14971  if (FD->getDescribedFunctionTemplate())
14972  return false;
14973 
14974  // Don't warn about function template specializations.
14976  return false;
14977 
14978  // Don't warn for OpenCL kernels.
14979  if (FD->hasAttr<OpenCLKernelAttr>())
14980  return false;
14981 
14982  // Don't warn on explicitly deleted functions.
14983  if (FD->isDeleted())
14984  return false;
14985 
14986  // Don't warn on implicitly local functions (such as having local-typed
14987  // parameters).
14988  if (!FD->isExternallyVisible())
14989  return false;
14990 
14991  // If we were able to find a potential prototype, don't warn.
14992  if (FindPossiblePrototype(FD, PossiblePrototype))
14993  return false;
14994 
14995  return true;
14996 }
14997 
14998 void
15000  const FunctionDecl *EffectiveDefinition,
15001  SkipBodyInfo *SkipBody) {
15002  const FunctionDecl *Definition = EffectiveDefinition;
15003  if (!Definition &&
15004  !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15005  return;
15006 
15007  if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15008  if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15009  if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15010  // A merged copy of the same function, instantiated as a member of
15011  // the same class, is OK.
15012  if (declaresSameEntity(OrigFD, OrigDef) &&
15013  declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15014  cast<Decl>(FD->getLexicalDeclContext())))
15015  return;
15016  }
15017  }
15018  }
15019 
15020  if (canRedefineFunction(Definition, getLangOpts()))
15021  return;
15022 
15023  // Don't emit an error when this is redefinition of a typo-corrected
15024  // definition.
15025  if (TypoCorrectedFunctionDefinitions.count(Definition))
15026  return;
15027 
15028  // If we don't have a visible definition of the function, and it's inline or
15029  // a template, skip the new definition.
15030  if (SkipBody && !hasVisibleDefinition(Definition) &&
15031  (Definition->getFormalLinkage() == InternalLinkage ||
15032  Definition->isInlined() ||
15033  Definition->getDescribedFunctionTemplate() ||
15034  Definition->getNumTemplateParameterLists())) {
15035  SkipBody->ShouldSkip = true;
15036  SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15037  if (auto *TD = Definition->getDescribedFunctionTemplate())
15038  makeMergedDefinitionVisible(TD);
15039  makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
15040  return;
15041  }
15042 
15043  if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15044  Definition->getStorageClass() == SC_Extern)
15045  Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15046  << FD << getLangOpts().CPlusPlus;
15047  else
15048  Diag(FD->getLocation(), diag::err_redefinition) << FD;
15049 
15050  Diag(Definition->getLocation(), diag::note_previous_definition);
15051  FD->setInvalidDecl();
15052 }
15053 
15054 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
15055  Sema &S) {
15056  CXXRecordDecl *const LambdaClass = CallOperator->getParent();
15057 
15058  LambdaScopeInfo *LSI = S.PushLambdaScope();
15059  LSI->CallOperator = CallOperator;
15060  LSI->Lambda = LambdaClass;
15061  LSI->ReturnType = CallOperator->getReturnType();
15062  const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15063 
15064  if (LCD == LCD_None)
15066  else if (LCD == LCD_ByCopy)
15068  else if (LCD == LCD_ByRef)
15070  DeclarationNameInfo DNI = CallOperator->getNameInfo();
15071 
15073  LSI->Mutable = !CallOperator->isConst();
15074 
15075  // Add the captures to the LSI so they can be noted as already
15076  // captured within tryCaptureVar.
15077  auto I = LambdaClass->field_begin();
15078  for (const auto &C : LambdaClass->captures()) {
15079  if (C.capturesVariable()) {
15080  ValueDecl *VD = C.getCapturedVar();
15081  if (VD->isInitCapture())
15083  const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15084  LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15085  /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15086  /*EllipsisLoc*/C.isPackExpansion()
15087  ? C.getEllipsisLoc() : SourceLocation(),
15088  I->getType(), /*Invalid*/false);
15089 
15090  } else if (C.capturesThis()) {
15091  LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15092  C.getCaptureKind() == LCK_StarThis);
15093  } else {
15094  LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15095  I->getType());
15096  }
15097  ++I;
15098  }
15099 }
15100 
15102  SkipBodyInfo *SkipBody,
15103  FnBodyKind BodyKind) {
15104  if (!D) {
15105  // Parsing the function declaration failed in some way. Push on a fake scope
15106  // anyway so we can try to parse the function body.
15107  PushFunctionScope();
15108  PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15109  return D;
15110  }
15111 
15112  FunctionDecl *FD = nullptr;
15113 
15114  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15115  FD = FunTmpl->getTemplatedDecl();
15116  else
15117  FD = cast<FunctionDecl>(D);
15118 
15119  // Do not push if it is a lambda because one is already pushed when building
15120  // the lambda in ActOnStartOfLambdaDefinition().
15121  if (!isLambdaCallOperator(FD))
15122  // [expr.const]/p14.1
15123  // An expression or conversion is in an immediate function context if it is
15124  // potentially evaluated and either: its innermost enclosing non-block scope
15125  // is a function parameter scope of an immediate function.
15126  PushExpressionEvaluationContext(
15127  FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
15128  : ExprEvalContexts.back().Context);
15129 
15130  // Check for defining attributes before the check for redefinition.
15131  if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15132  Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15133  FD->dropAttr<AliasAttr>();
15134  FD->setInvalidDecl();
15135  }
15136  if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15137  Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15138  FD->dropAttr<IFuncAttr>();
15139  FD->setInvalidDecl();
15140  }
15141  if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15142  if (!Context.getTargetInfo().hasFeature("fmv") &&
15143  !Attr->isDefaultVersion()) {
15144  // If function multi versioning disabled skip parsing function body
15145  // defined with non-default target_version attribute
15146  if (SkipBody)
15147  SkipBody->ShouldSkip = true;
15148  return nullptr;
15149  }
15150  }
15151 
15152  if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15153  if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15154  Ctor->isDefaultConstructor() &&
15155  Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15156  // If this is an MS ABI dllexport default constructor, instantiate any
15157  // default arguments.
15158  InstantiateDefaultCtorDefaultArgs(Ctor);
15159  }
15160  }
15161 
15162  // See if this is a redefinition. If 'will have body' (or similar) is already
15163  // set, then these checks were already performed when it was set.
15164  if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15166  CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15167 
15168  // If we're skipping the body, we're done. Don't enter the scope.
15169  if (SkipBody && SkipBody->ShouldSkip)
15170  return D;
15171  }
15172 
15173  // Mark this function as "will have a body eventually". This lets users to
15174  // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15175  // this function.
15176  FD->setWillHaveBody();
15177 
15178  // If we are instantiating a generic lambda call operator, push
15179  // a LambdaScopeInfo onto the function stack. But use the information
15180  // that's already been calculated (ActOnLambdaExpr) to prime the current
15181  // LambdaScopeInfo.
15182  // When the template operator is being specialized, the LambdaScopeInfo,
15183  // has to be properly restored so that tryCaptureVariable doesn't try
15184  // and capture any new variables. In addition when calculating potential
15185  // captures during transformation of nested lambdas, it is necessary to
15186  // have the LSI properly restored.
15188  assert(inTemplateInstantiation() &&
15189  "There should be an active template instantiation on the stack "
15190  "when instantiating a generic lambda!");
15191  RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
15192  } else {
15193  // Enter a new function scope
15194  PushFunctionScope();
15195  }
15196 
15197  // Builtin functions cannot be defined.
15198  if (unsigned BuiltinID = FD->getBuiltinID()) {
15199  if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
15200  !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
15201  Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15202  FD->setInvalidDecl();
15203  }
15204  }
15205 
15206  // The return type of a function definition must be complete (C99 6.9.1p3),
15207  // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
15208  QualType ResultType = FD->getReturnType();
15209  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15210  !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15211  RequireCompleteType(FD->getLocation(), ResultType,
15212  diag::err_func_def_incomplete_result))
15213  FD->setInvalidDecl();
15214 
15215  if (FnBodyScope)
15216  PushDeclContext(FnBodyScope, FD);
15217 
15218  // Check the validity of our function parameters
15219  if (BodyKind != FnBodyKind::Delete)
15220  CheckParmsForFunctionDef(FD->parameters(),
15221  /*CheckParameterNames=*/true);
15222 
15223  // Add non-parameter declarations already in the function to the current
15224  // scope.
15225  if (FnBodyScope) {
15226  for (Decl *NPD : FD->decls()) {
15227  auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15228  if (!NonParmDecl)
15229  continue;
15230  assert(!isa<ParmVarDecl>(NonParmDecl) &&
15231  "parameters should not be in newly created FD yet");
15232 
15233  // If the decl has a name, make it accessible in the current scope.
15234  if (NonParmDecl->getDeclName())
15235  PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15236 
15237  // Similarly, dive into enums and fish their constants out, making them
15238  // accessible in this scope.
15239  if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15240  for (auto *EI : ED->enumerators())
15241  PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15242  }
15243  }
15244  }
15245 
15246  // Introduce our parameters into the function scope
15247  for (auto *Param : FD->parameters()) {
15248  Param->setOwningFunction(FD);
15249 
15250  // If this has an identifier, add it to the scope stack.
15251  if (Param->getIdentifier() && FnBodyScope) {
15252  CheckShadow(FnBodyScope, Param);
15253 
15254  PushOnScopeChains(Param, FnBodyScope);
15255  }
15256  }
15257 
15258  // C++ [module.import/6] external definitions are not permitted in header
15259  // units. Deleted and Defaulted functions are implicitly inline (but the
15260  // inline state is not set at this point, so check the BodyKind explicitly).
15261  // FIXME: Consider an alternate location for the test where the inlined()
15262  // state is complete.
15263  if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15264  !FD->isInvalidDecl() && !FD->isInlined() &&
15265  BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15267  !FD->isTemplated() && !FD->isTemplateInstantiation()) {
15268  assert(FD->isThisDeclarationADefinition());
15269  Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15270  FD->setInvalidDecl();
15271  }
15272 
15273  // Ensure that the function's exception specification is instantiated.
15274  if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15275  ResolveExceptionSpec(D->getLocation(), FPT);
15276 
15277  // dllimport cannot be applied to non-inline function definitions.
15278  if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15279  !FD->isTemplateInstantiation()) {
15280  assert(!FD->hasAttr<DLLExportAttr>());
15281  Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15282  FD->setInvalidDecl();
15283  return D;
15284  }
15285  // We want to attach documentation to original Decl (which might be
15286  // a function template).
15287  ActOnDocumentableDecl(D);
15288  if (getCurLexicalContext()->isObjCContainer() &&
15289  getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15290  getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15291  Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15292 
15293  return D;
15294 }
15295 
15296 /// Given the set of return statements within a function body,
15297 /// compute the variables that are subject to the named return value
15298 /// optimization.
15299 ///
15300 /// Each of the variables that is subject to the named return value
15301 /// optimization will be marked as NRVO variables in the AST, and any
15302 /// return statement that has a marked NRVO variable as its NRVO candidate can
15303 /// use the named return value optimization.
15304 ///
15305 /// This function applies a very simplistic algorithm for NRVO: if every return
15306 /// statement in the scope of a variable has the same NRVO candidate, that
15307 /// candidate is an NRVO variable.
15309  ReturnStmt **Returns = Scope->Returns.data();
15310 
15311  for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15312  if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15313  if (!NRVOCandidate->isNRVOVariable())
15314  Returns[I]->setNRVOCandidate(nullptr);
15315  }
15316  }
15317 }
15318 
15320  // We can't delay parsing the body of a constexpr function template (yet).
15322  return false;
15323 
15324  // We can't delay parsing the body of a function template with a deduced
15325  // return type (yet).
15326  if (D.getDeclSpec().hasAutoTypeSpec()) {
15327  // If the placeholder introduces a non-deduced trailing return type,
15328  // we can still delay parsing it.
15329  if (D.getNumTypeObjects()) {
15330  const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15331  if (Outer.Kind == DeclaratorChunk::Function &&
15332  Outer.Fun.hasTrailingReturnType()) {
15333  QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15334  return Ty.isNull() || !Ty->isUndeducedType();
15335  }
15336  }
15337  return false;
15338  }
15339 
15340  return true;
15341 }
15342 
15344  // We cannot skip the body of a function (or function template) which is
15345  // constexpr, since we may need to evaluate its body in order to parse the
15346  // rest of the file.
15347  // We cannot skip the body of a function with an undeduced return type,
15348  // because any callers of that function need to know the type.
15349  if (const FunctionDecl *FD = D->getAsFunction()) {
15350  if (FD->isConstexpr())
15351  return false;
15352  // We can't simply call Type::isUndeducedType here, because inside template
15353  // auto can be deduced to a dependent type, which is not considered
15354  // "undeduced".
15355  if (FD->getReturnType()->getContainedDeducedType())
15356  return false;
15357  }
15358  return Consumer.shouldSkipFunctionBody(D);
15359 }
15360 
15362  if (!Decl)
15363  return nullptr;
15364  if (FunctionDecl *FD = Decl->getAsFunction())
15365  FD->setHasSkippedBody();
15366  else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15367  MD->setHasSkippedBody();
15368  return Decl;
15369 }
15370 
15372  return ActOnFinishFunctionBody(D, BodyArg, false);
15373 }
15374 
15375 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
15376 /// body.
15378 public:
15379  ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
15381  if (!IsLambda)
15383  }
15384 
15385 private:
15386  Sema &S;
15387  bool IsLambda = false;
15388 };
15389 
15391  llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15392 
15393  auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15394  if (EscapeInfo.count(BD))
15395  return EscapeInfo[BD];
15396 
15397  bool R = false;
15398  const BlockDecl *CurBD = BD;
15399 
15400  do {
15401  R = !CurBD->doesNotEscape();
15402  if (R)
15403  break;
15404  CurBD = CurBD->getParent()->getInnermostBlockDecl();
15405  } while (CurBD);
15406 
15407  return EscapeInfo[BD] = R;
15408  };
15409 
15410  // If the location where 'self' is implicitly retained is inside a escaping
15411  // block, emit a diagnostic.
15412  for (const std::pair<SourceLocation, const BlockDecl *> &P :
15414  if (IsOrNestedInEscapingBlock(P.second))
15415  S.Diag(P.first, diag::warn_implicitly_retains_self)
15416  << FixItHint::CreateInsertion(P.first, "self->");
15417 }
15418 
15420  bool IsInstantiation) {
15421  FunctionScopeInfo *FSI = getCurFunction();
15422  FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
15423 
15424  if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
15425  FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15426 
15427  sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15428  sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15429 
15430  if (getLangOpts().Coroutines && FSI->isCoroutine())
15431  CheckCompletedCoroutineBody(FD, Body);
15432 
15433  {
15434  // Do not call PopExpressionEvaluationContext() if it is a lambda because
15435  // one is already popped when finishing the lambda in BuildLambdaExpr().
15436  // This is meant to pop the context added in ActOnStartOfFunctionDef().
15437  ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
15438 
15439  if (FD) {
15440  FD->setBody(Body);
15441  FD->setWillHaveBody(false);
15442 
15443  if (getLangOpts().CPlusPlus14) {
15444  if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
15445  FD->getReturnType()->isUndeducedType()) {
15446  // For a function with a deduced result type to return void,
15447  // the result type as written must be 'auto' or 'decltype(auto)',
15448  // possibly cv-qualified or constrained, but not ref-qualified.
15449  if (!FD->getReturnType()->getAs<AutoType>()) {
15450  Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
15451  << FD->getReturnType();
15452  FD->setInvalidDecl();
15453  } else {
15454  // Falling off the end of the function is the same as 'return;'.
15455  Expr *Dummy = nullptr;
15456  if (DeduceFunctionTypeFromReturnExpr(
15457  FD, dcl->getLocation(), Dummy,
15458  FD->getReturnType()->getAs<AutoType>()))
15459  FD->setInvalidDecl();
15460  }
15461  }
15462  } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
15463  // In C++11, we don't use 'auto' deduction rules for lambda call
15464  // operators because we don't support return type deduction.
15465  auto *LSI = getCurLambda();
15466  if (LSI->HasImplicitReturnType) {
15467  deduceClosureReturnType(*LSI);
15468 
15469  // C++11 [expr.prim.lambda]p4:
15470  // [...] if there are no return statements in the compound-statement
15471  // [the deduced type is] the type void
15472  QualType RetType =
15473  LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
15474 
15475  // Update the return type to the deduced type.
15476  const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
15477  FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
15478  Proto->getExtProtoInfo()));
15479  }
15480  }
15481 
15482  // If the function implicitly returns zero (like 'main') or is naked,
15483  // don't complain about missing return statements.
15484  if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
15486 
15487  // MSVC permits the use of pure specifier (=0) on function definition,
15488  // defined at class scope, warn about this non-standard construct.
15489  if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
15490  Diag(FD->getLocation(), diag::ext_pure_function_definition);
15491 
15492  if (!FD->isInvalidDecl()) {
15493  // Don't diagnose unused parameters of defaulted, deleted or naked
15494  // functions.
15495  if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
15496  !FD->hasAttr<NakedAttr>())
15497  DiagnoseUnusedParameters(FD->parameters());
15498  DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
15499  FD->getReturnType(), FD);
15500 
15501  // If this is a structor, we need a vtable.
15502  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
15503  MarkVTableUsed(FD->getLocation(), Constructor->getParent());
15504  else if (CXXDestructorDecl *Destructor =
15505  dyn_cast<CXXDestructorDecl>(FD))
15506  MarkVTableUsed(FD->getLocation(), Destructor->getParent());
15507 
15508  // Try to apply the named return value optimization. We have to check
15509  // if we can do this here because lambdas keep return statements around
15510  // to deduce an implicit return type.
15511  if (FD->getReturnType()->isRecordType() &&
15512  (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
15513  computeNRVO(Body, FSI);
15514  }
15515 
15516  // GNU warning -Wmissing-prototypes:
15517  // Warn if a global function is defined without a previous
15518  // prototype declaration. This warning is issued even if the
15519  // definition itself provides a prototype. The aim is to detect
15520  // global functions that fail to be declared in header files.
15521  const FunctionDecl *PossiblePrototype = nullptr;
15522  if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
15523  Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
15524 
15525  if (PossiblePrototype) {
15526  // We found a declaration that is not a prototype,
15527  // but that could be a zero-parameter prototype
15528  if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
15529  TypeLoc TL = TI->getTypeLoc();
15531  Diag(PossiblePrototype->getLocation(),
15532  diag::note_declaration_not_a_prototype)
15533  << (FD->getNumParams() != 0)
15534  << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
15535  FTL.getRParenLoc(), "void")
15536  : FixItHint{});
15537  }
15538  } else {
15539  // Returns true if the token beginning at this Loc is `const`.
15540  auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
15541  const LangOptions &LangOpts) {
15542  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
15543  if (LocInfo.first.isInvalid())
15544  return false;
15545 
15546  bool Invalid = false;
15547  StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
15548  if (Invalid)
15549  return false;
15550 
15551  if (LocInfo.second > Buffer.size())
15552  return false;
15553 
15554  const char *LexStart = Buffer.data() + LocInfo.second;
15555  StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
15556 
15557  return StartTok.consume_front("const") &&
15558  (StartTok.empty() || isWhitespace(StartTok[0]) ||
15559  StartTok.startswith("/*") || StartTok.startswith("//"));
15560  };
15561 
15562  auto findBeginLoc = [&]() {
15563  // If the return type has `const` qualifier, we want to insert
15564  // `static` before `const` (and not before the typename).
15565  if ((FD->getReturnType()->isAnyPointerType() &&
15567  FD->getReturnType().isConstQualified()) {
15568  // But only do this if we can determine where the `const` is.
15569 
15570  if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15571  getLangOpts()))
15572 
15573  return FD->getBeginLoc();
15574  }
15575  return FD->getTypeSpecStartLoc();
15576  };
15577  Diag(FD->getTypeSpecStartLoc(),
15578  diag::note_static_for_internal_linkage)
15579  << /* function */ 1
15580  << (FD->getStorageClass() == SC_None
15581  ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15582  : FixItHint{});
15583  }
15584  }
15585 
15586  // We might not have found a prototype because we didn't wish to warn on
15587  // the lack of a missing prototype. Try again without the checks for
15588  // whether we want to warn on the missing prototype.
15589  if (!PossiblePrototype)
15590  (void)FindPossiblePrototype(FD, PossiblePrototype);
15591 
15592  // If the function being defined does not have a prototype, then we may
15593  // need to diagnose it as changing behavior in C2x because we now know
15594  // whether the function accepts arguments or not. This only handles the
15595  // case where the definition has no prototype but does have parameters
15596  // and either there is no previous potential prototype, or the previous
15597  // potential prototype also has no actual prototype. This handles cases
15598  // like:
15599  // void f(); void f(a) int a; {}
15600  // void g(a) int a; {}
15601  // See MergeFunctionDecl() for other cases of the behavior change
15602  // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15603  // type without a prototype.
15604  if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15605  (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15606  !PossiblePrototype->isImplicit()))) {
15607  // The function definition has parameters, so this will change behavior
15608  // in C2x. If there is a possible prototype, it comes before the
15609  // function definition.
15610  // FIXME: The declaration may have already been diagnosed as being
15611  // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15612  // there's no way to test for the "changes behavior" condition in
15613  // SemaType.cpp when forming the declaration's function type. So, we do
15614  // this awkward dance instead.
15615  //
15616  // If we have a possible prototype and it declares a function with a
15617  // prototype, we don't want to diagnose it; if we have a possible
15618  // prototype and it has no prototype, it may have already been
15619  // diagnosed in SemaType.cpp as deprecated depending on whether
15620  // -Wstrict-prototypes is enabled. If we already warned about it being
15621  // deprecated, add a note that it also changes behavior. If we didn't
15622  // warn about it being deprecated (because the diagnostic is not
15623  // enabled), warn now that it is deprecated and changes behavior.
15624 
15625  // This K&R C function definition definitely changes behavior in C2x,
15626  // so diagnose it.
15627  Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
15628  << /*definition*/ 1 << /* not supported in C2x */ 0;
15629 
15630  // If we have a possible prototype for the function which is a user-
15631  // visible declaration, we already tested that it has no prototype.
15632  // This will change behavior in C2x. This gets a warning rather than a
15633  // note because it's the same behavior-changing problem as with the
15634  // definition.
15635  if (PossiblePrototype)
15636  Diag(PossiblePrototype->getLocation(),
15637  diag::warn_non_prototype_changes_behavior)
15638  << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
15639  << /*definition*/ 1;
15640  }
15641 
15642  // Warn on CPUDispatch with an actual body.
15643  if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
15644  if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
15645  if (!CmpndBody->body_empty())
15646  Diag(CmpndBody->body_front()->getBeginLoc(),
15647  diag::warn_dispatch_body_ignored);
15648 
15649  if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
15650  const CXXMethodDecl *KeyFunction;
15651  if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
15652  MD->isVirtual() &&
15653  (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
15654  MD == KeyFunction->getCanonicalDecl()) {
15655  // Update the key-function state if necessary for this ABI.
15656  if (FD->isInlined() &&
15658  Context.setNonKeyFunction(MD);
15659 
15660  // If the newly-chosen key function is already defined, then we
15661  // need to mark the vtable as used retroactively.
15662  KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
15663  const FunctionDecl *Definition;
15664  if (KeyFunction && KeyFunction->isDefined(Definition))
15665  MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
15666  } else {
15667  // We just defined they key function; mark the vtable as used.
15668  MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
15669  }
15670  }
15671  }
15672 
15673  assert(
15674  (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
15675  "Function parsing confused");
15676  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
15677  assert(MD == getCurMethodDecl() && "Method parsing confused");
15678  MD->setBody(Body);
15679  if (!MD->isInvalidDecl()) {
15680  DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
15681  MD->getReturnType(), MD);
15682 
15683  if (Body)
15684  computeNRVO(Body, FSI);
15685  }
15686  if (FSI->ObjCShouldCallSuper) {
15687  Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
15688  << MD->getSelector().getAsString();
15689  FSI->ObjCShouldCallSuper = false;
15690  }
15692  const ObjCMethodDecl *InitMethod = nullptr;
15693  bool isDesignated =
15694  MD->isDesignatedInitializerForTheInterface(&InitMethod);
15695  assert(isDesignated && InitMethod);
15696  (void)isDesignated;
15697 
15698  auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
15699  auto IFace = MD->getClassInterface();
15700  if (!IFace)
15701  return false;
15702  auto SuperD = IFace->getSuperClass();
15703  if (!SuperD)
15704  return false;
15705  return SuperD->getIdentifier() ==
15706  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
15707  };
15708  // Don't issue this warning for unavailable inits or direct subclasses
15709  // of NSObject.
15710  if (!MD->isUnavailable() && !superIsNSObject(MD)) {
15711  Diag(MD->getLocation(),
15712  diag::warn_objc_designated_init_missing_super_call);
15713  Diag(InitMethod->getLocation(),
15714  diag::note_objc_designated_init_marked_here);
15715  }
15716  FSI->ObjCWarnForNoDesignatedInitChain = false;
15717  }
15718  if (FSI->ObjCWarnForNoInitDelegation) {
15719  // Don't issue this warning for unavaialable inits.
15720  if (!MD->isUnavailable())
15721  Diag(MD->getLocation(),
15722  diag::warn_objc_secondary_init_missing_init_call);
15723  FSI->ObjCWarnForNoInitDelegation = false;
15724  }
15725 
15727  } else {
15728  // Parsing the function declaration failed in some way. Pop the fake scope
15729  // we pushed on.
15730  PopFunctionScopeInfo(ActivePolicy, dcl);
15731  return nullptr;
15732  }
15733 
15734  if (Body && FSI->HasPotentialAvailabilityViolations)
15735  DiagnoseUnguardedAvailabilityViolations(dcl);
15736 
15737  assert(!FSI->ObjCShouldCallSuper &&
15738  "This should only be set for ObjC methods, which should have been "
15739  "handled in the block above.");
15740 
15741  // Verify and clean out per-function state.
15742  if (Body && (!FD || !FD->isDefaulted())) {
15743  // C++ constructors that have function-try-blocks can't have return
15744  // statements in the handlers of that block. (C++ [except.handle]p14)
15745  // Verify this.
15746  if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15747  DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15748 
15749  // Verify that gotos and switch cases don't jump into scopes illegally.
15750  if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
15751  DiagnoseInvalidJumps(Body);
15752 
15753  if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
15754  if (!Destructor->getParent()->isDependentType())
15755  CheckDestructor(Destructor);
15756 
15757  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15758  Destructor->getParent());
15759  }
15760 
15761  // If any errors have occurred, clear out any temporaries that may have
15762  // been leftover. This ensures that these temporaries won't be picked up
15763  // for deletion in some later function.
15764  if (hasUncompilableErrorOccurred() ||
15765  getDiagnostics().getSuppressAllDiagnostics()) {
15766  DiscardCleanupsInEvaluationContext();
15767  }
15768  if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15769  // Since the body is valid, issue any analysis-based warnings that are
15770  // enabled.
15771  ActivePolicy = &WP;
15772  }
15773 
15774  if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
15775  !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
15776  FD->setInvalidDecl();
15777 
15778  if (FD && FD->hasAttr<NakedAttr>()) {
15779  for (const Stmt *S : Body->children()) {
15780  // Allow local register variables without initializer as they don't
15781  // require prologue.
15782  bool RegisterVariables = false;
15783  if (auto *DS = dyn_cast<DeclStmt>(S)) {
15784  for (const auto *Decl : DS->decls()) {
15785  if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
15786  RegisterVariables =
15787  Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15788  if (!RegisterVariables)
15789  break;
15790  }
15791  }
15792  }
15793  if (RegisterVariables)
15794  continue;
15795  if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15796  Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15797  Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15798  FD->setInvalidDecl();
15799  break;
15800  }
15801  }
15802  }
15803 
15804  assert(ExprCleanupObjects.size() ==
15805  ExprEvalContexts.back().NumCleanupObjects &&
15806  "Leftover temporaries in function");
15807  assert(!Cleanup.exprNeedsCleanups() &&
15808  "Unaccounted cleanups in function");
15809  assert(MaybeODRUseExprs.empty() &&
15810  "Leftover expressions for odr-use checking");
15811  }
15812  } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15813  // the declaration context below. Otherwise, we're unable to transform
15814  // 'this' expressions when transforming immediate context functions.
15815 
15816  if (!IsInstantiation)
15817  PopDeclContext();
15818 
15819  PopFunctionScopeInfo(ActivePolicy, dcl);
15820  // If any errors have occurred, clear out any temporaries that may have
15821  // been leftover. This ensures that these temporaries won't be picked up for
15822  // deletion in some later function.
15823  if (hasUncompilableErrorOccurred()) {
15824  DiscardCleanupsInEvaluationContext();
15825  }
15826 
15827  if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15828  !LangOpts.OMPTargetTriples.empty())) ||
15829  LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15830  auto ES = getEmissionStatus(FD);
15833  DeclsToCheckForDeferredDiags.insert(FD);
15834  }
15835 
15836  if (FD && !FD->isDeleted())
15837  checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15838 
15839  return dcl;
15840 }
15841 
15842 /// When we finish delayed parsing of an attribute, we must attach it to the
15843 /// relevant Decl.
15845  ParsedAttributes &Attrs) {
15846  // Always attach attributes to the underlying decl.
15847  if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15848  D = TD->getTemplatedDecl();
15849  ProcessDeclAttributeList(S, D, Attrs);
15850 
15851  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15852  if (Method->isStatic())
15853  checkThisInStaticMemberFunctionAttributes(Method);
15854 }
15855 
15856 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15857 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15859  IdentifierInfo &II, Scope *S) {
15860  // It is not valid to implicitly define a function in C2x.
15861  assert(LangOpts.implicitFunctionsAllowed() &&
15862  "Implicit function declarations aren't allowed in this language mode");
15863 
15864  // Find the scope in which the identifier is injected and the corresponding
15865  // DeclContext.
15866  // FIXME: C89 does not say what happens if there is no enclosing block scope.
15867  // In that case, we inject the declaration into the translation unit scope
15868  // instead.
15869  Scope *BlockScope = S;
15870  while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15871  BlockScope = BlockScope->getParent();
15872 
15873  Scope *ContextScope = BlockScope;
15874  while (!ContextScope->getEntity())
15875  ContextScope = ContextScope->getParent();
15876  ContextRAII SavedContext(*this, ContextScope->getEntity());
15877 
15878  // Before we produce a declaration for an implicitly defined
15879  // function, see whether there was a locally-scoped declaration of
15880  // this name as a function or variable. If so, use that
15881  // (non-visible) declaration, and complain about it.
15882  NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15883  if (ExternCPrev) {
15884  // We still need to inject the function into the enclosing block scope so
15885  // that later (non-call) uses can see it.
15886  PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15887 
15888  // C89 footnote 38:
15889  // If in fact it is not defined as having type "function returning int",
15890  // the behavior is undefined.
15891  if (!isa<FunctionDecl>(ExternCPrev) ||
15892  !Context.typesAreCompatible(
15893  cast<FunctionDecl>(ExternCPrev)->getType(),
15894  Context.getFunctionNoProtoType(Context.IntTy))) {
15895  Diag(Loc, diag::ext_use_out_of_scope_declaration)
15896  << ExternCPrev << !getLangOpts().C99;
15897  Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15898  return ExternCPrev;
15899  }
15900  }
15901 
15902  // Extension in C99 (defaults to error). Legal in C89, but warn about it.
15903  unsigned diag_id;
15904  if (II.getName().startswith("__builtin_"))
15905  diag_id = diag::warn_builtin_unknown;
15906  // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15907  else if (getLangOpts().C99)
15908  diag_id = diag::ext_implicit_function_decl_c99;
15909  else
15910  diag_id = diag::warn_implicit_function_decl;
15911 
15912  TypoCorrection Corrected;
15913  // Because typo correction is expensive, only do it if the implicit
15914  // function declaration is going to be treated as an error.
15915  //
15916  // Perform the correction before issuing the main diagnostic, as some
15917  // consumers use typo-correction callbacks to enhance the main diagnostic.
15918  if (S && !ExternCPrev &&
15919  (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15921  Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15922  S, nullptr, CCC, CTK_NonError);
15923  }
15924 
15925  Diag(Loc, diag_id) << &II;
15926  if (Corrected) {
15927  // If the correction is going to suggest an implicitly defined function,
15928  // skip the correction as not being a particularly good idea.
15929  bool Diagnose = true;
15930  if (const auto *D = Corrected.getCorrectionDecl())
15931  Diagnose = !D->isImplicit();
15932  if (Diagnose)
15933  diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15934  /*ErrorRecovery*/ false);
15935  }
15936 
15937  // If we found a prior declaration of this function, don't bother building
15938  // another one. We've already pushed that one into scope, so there's nothing
15939  // more to do.
15940  if (ExternCPrev)
15941  return ExternCPrev;
15942 
15943  // Set a Declarator for the implicit definition: int foo();
15944  const char *Dummy;
15945  AttributeFactory attrFactory;
15946  DeclSpec DS(attrFactory);
15947  unsigned DiagID;
15948  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15949  Context.getPrintingPolicy());
15950  (void)Error; // Silence warning.
15951  assert(!Error && "Error setting up implicit decl!");
15952  SourceLocation NoLoc;
15954  D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15955  /*IsAmbiguous=*/false,
15956  /*LParenLoc=*/NoLoc,
15957  /*Params=*/nullptr,
15958  /*NumParams=*/0,
15959  /*EllipsisLoc=*/NoLoc,
15960  /*RParenLoc=*/NoLoc,
15961  /*RefQualifierIsLvalueRef=*/true,
15962  /*RefQualifierLoc=*/NoLoc,
15963  /*MutableLoc=*/NoLoc, EST_None,
15964  /*ESpecRange=*/SourceRange(),
15965  /*Exceptions=*/nullptr,
15966  /*ExceptionRanges=*/nullptr,
15967  /*NumExceptions=*/0,
15968  /*NoexceptExpr=*/nullptr,
15969  /*ExceptionSpecTokens=*/nullptr,
15970  /*DeclsInPrototype=*/std::nullopt,
15971  Loc, Loc, D),
15972  std::move(DS.getAttributes()), SourceLocation());
15973  D.SetIdentifier(&II, Loc);
15974 
15975  // Insert this function into the enclosing block scope.
15976  FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15977  FD->setImplicit();
15978 
15979  AddKnownFunctionAttributes(FD);
15980 
15981  return FD;
15982 }
15983 
15984 /// If this function is a C++ replaceable global allocation function
15985 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15986 /// adds any function attributes that we know a priori based on the standard.
15987 ///
15988 /// We need to check for duplicate attributes both here and where user-written
15989 /// attributes are applied to declarations.
15991  FunctionDecl *FD) {
15992  if (FD->isInvalidDecl())
15993  return;
15994 
15995  if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15996  FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15997  return;
15998 
15999  std::optional<unsigned> AlignmentParam;
16000  bool IsNothrow = false;
16001  if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16002  return;
16003 
16004  // C++2a [basic.stc.dynamic.allocation]p4:
16005  // An allocation function that has a non-throwing exception specification
16006  // indicates failure by returning a null pointer value. Any other allocation
16007  // function never returns a null pointer value and indicates failure only by
16008  // throwing an exception [...]
16009  if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
16010  FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16011 
16012  // C++2a [basic.stc.dynamic.allocation]p2:
16013  // An allocation function attempts to allocate the requested amount of
16014  // storage. [...] If the request succeeds, the value returned by a
16015  // replaceable allocation function is a [...] pointer value p0 different
16016  // from any previously returned value p1 [...]
16017  //
16018  // However, this particular information is being added in codegen,
16019  // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16020 
16021  // C++2a [basic.stc.dynamic.allocation]p2:
16022  // An allocation function attempts to allocate the requested amount of
16023  // storage. If it is successful, it returns the address of the start of a
16024  // block of storage whose length in bytes is at least as large as the
16025  // requested size.
16026  if (!FD->hasAttr<AllocSizeAttr>()) {
16027  FD->addAttr(AllocSizeAttr::CreateImplicit(
16028  Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16029  /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16030  }
16031 
16032  // C++2a [basic.stc.dynamic.allocation]p3:
16033  // For an allocation function [...], the pointer returned on a successful
16034  // call shall represent the address of storage that is aligned as follows:
16035  // (3.1) If the allocation function takes an argument of type
16036  // std​::​align_­val_­t, the storage will have the alignment
16037  // specified by the value of this argument.
16038  if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16039  FD->addAttr(AllocAlignAttr::CreateImplicit(
16040  Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16041  }
16042 
16043  // FIXME:
16044  // C++2a [basic.stc.dynamic.allocation]p3:
16045  // For an allocation function [...], the pointer returned on a successful
16046  // call shall represent the address of storage that is aligned as follows:
16047  // (3.2) Otherwise, if the allocation function is named operator new[],
16048  // the storage is aligned for any object that does not have
16049  // new-extended alignment ([basic.align]) and is no larger than the
16050  // requested size.
16051  // (3.3) Otherwise, the storage is aligned for any object that does not
16052  // have new-extended alignment and is of the requested size.
16053 }
16054 
16055 /// Adds any function attributes that we know a priori based on
16056 /// the declaration of this function.
16057 ///
16058 /// These attributes can apply both to implicitly-declared builtins
16059 /// (like __builtin___printf_chk) or to library-declared functions
16060 /// like NSLog or printf.
16061 ///
16062 /// We need to check for duplicate attributes both here and where user-written
16063 /// attributes are applied to declarations.
16065  if (FD->isInvalidDecl())
16066  return;
16067 
16068  // If this is a built-in function, map its builtin attributes to
16069  // actual attributes.
16070  if (unsigned BuiltinID = FD->getBuiltinID()) {
16071  // Handle printf-formatting attributes.
16072  unsigned FormatIdx;
16073  bool HasVAListArg;
16074  if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16075  if (!FD->hasAttr<FormatAttr>()) {
16076  const char *fmt = "printf";
16077  unsigned int NumParams = FD->getNumParams();
16078  if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16079  FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16080  fmt = "NSString";
16081  FD->addAttr(FormatAttr::CreateImplicit(Context,
16082  &Context.Idents.get(fmt),
16083  FormatIdx+1,
16084  HasVAListArg ? 0 : FormatIdx+2,
16085  FD->getLocation()));
16086  }
16087  }
16088  if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16089  HasVAListArg)) {
16090  if (!FD->hasAttr<FormatAttr>())
16091  FD->addAttr(FormatAttr::CreateImplicit(Context,
16092  &Context.Idents.get("scanf"),
16093  FormatIdx+1,
16094  HasVAListArg ? 0 : FormatIdx+2,
16095  FD->getLocation()));
16096  }
16097 
16098  // Handle automatically recognized callbacks.
16100  if (!FD->hasAttr<CallbackAttr>() &&
16101  Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16102  FD->addAttr(CallbackAttr::CreateImplicit(
16103  Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16104 
16105  // Mark const if we don't care about errno and/or floating point exceptions
16106  // that are the only thing preventing the function from being const. This
16107  // allows IRgen to use LLVM intrinsics for such functions.
16108  bool NoExceptions =
16109  getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
16110  bool ConstWithoutErrnoAndExceptions =
16111  Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
16112  bool ConstWithoutExceptions =
16113  Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
16114  if (!FD->hasAttr<ConstAttr>() &&
16115  (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16116  (!ConstWithoutErrnoAndExceptions ||
16117  (!getLangOpts().MathErrno && NoExceptions)) &&
16118  (!ConstWithoutExceptions || NoExceptions))
16119  FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16120 
16121  // We make "fma" on GNU or Windows const because we know it does not set
16122  // errno in those environments even though it could set errno based on the
16123  // C standard.
16124  const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16125  if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16126  !FD->hasAttr<ConstAttr>()) {
16127  switch (BuiltinID) {
16128  case Builtin::BI__builtin_fma:
16129  case Builtin::BI__builtin_fmaf:
16130  case Builtin::BI__builtin_fmal:
16131  case Builtin::BIfma:
16132  case Builtin::BIfmaf:
16133  case Builtin::BIfmal:
16134  FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16135  break;
16136  default:
16137  break;
16138  }
16139  }
16140 
16141  if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16142  !FD->hasAttr<ReturnsTwiceAttr>())
16143  FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16144  FD->getLocation()));
16145  if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16146  FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16147  if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16148  FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16149  if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16150  FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16151  if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16152  !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16153  // Add the appropriate attribute, depending on the CUDA compilation mode
16154  // and which target the builtin belongs to. For example, during host
16155  // compilation, aux builtins are __device__, while the rest are __host__.
16156  if (getLangOpts().CUDAIsDevice !=
16157  Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
16158  FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16159  else
16160  FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16161  }
16162 
16163  // Add known guaranteed alignment for allocation functions.
16164  switch (BuiltinID) {
16165  case Builtin::BImemalign:
16166  case Builtin::BIaligned_alloc:
16167  if (!FD->hasAttr<AllocAlignAttr>())
16168  FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16169  FD->getLocation()));
16170  break;
16171  default:
16172  break;
16173  }
16174 
16175  // Add allocsize attribute for allocation functions.
16176  switch (BuiltinID) {
16177  case Builtin::BIcalloc:
16178  FD->addAttr(AllocSizeAttr::CreateImplicit(
16179  Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16180  break;
16181  case Builtin::BImemalign:
16182  case Builtin::BIaligned_alloc:
16183  case Builtin::BIrealloc:
16184  FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16185  ParamIdx(), FD->getLocation()));
16186  break;
16187  case Builtin::BImalloc:
16188  FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16189  ParamIdx(), FD->getLocation()));
16190  break;
16191  default:
16192  break;
16193  }
16194 
16195  // Add lifetime attribute to std::move, std::fowrard et al.
16196  switch (BuiltinID) {
16197  case Builtin::BIaddressof:
16198  case Builtin::BI__addressof:
16199  case Builtin::BI__builtin_addressof:
16200  case Builtin::BIas_const:
16201  case Builtin::BIforward:
16202  case Builtin::BIforward_like:
16203  case Builtin::BImove:
16204  case Builtin::BImove_if_noexcept:
16205  if (ParmVarDecl *P = FD->getParamDecl(0u);
16206  !P->hasAttr<LifetimeBoundAttr>())
16207  P->addAttr(
16208  LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
16209  break;
16210  default:
16211  break;
16212  }
16213  }
16214 
16215  AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
16216 
16217  // If C++ exceptions are enabled but we are told extern "C" functions cannot
16218  // throw, add an implicit nothrow attribute to any extern "C" function we come
16219  // across.
16220  if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16221  FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16222  const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16223  if (!FPT || FPT->getExceptionSpecType() == EST_None)
16224  FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16225  }
16226 
16227  IdentifierInfo *Name = FD->getIdentifier();
16228  if (!Name)
16229  return;
16230  if ((!getLangOpts().CPlusPlus &&
16231  FD->getDeclContext()->isTranslationUnit()) ||
16232  (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16233  cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16235  // Okay: this could be a libc/libm/Objective-C function we know
16236  // about.
16237  } else
16238  return;
16239 
16240  if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16241  // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16242  // target-specific builtins, perhaps?
16243  if (!FD->hasAttr<FormatAttr>())
16244  FD->addAttr(FormatAttr::CreateImplicit(Context,
16245  &Context.Idents.get("printf"), 2,
16246  Name->isStr("vasprintf") ? 0 : 3,
16247  FD->getLocation()));
16248  }
16249 
16250  if (Name->isStr("__CFStringMakeConstantString")) {
16251  // We already have a __builtin___CFStringMakeConstantString,
16252  // but builds that use -fno-constant-cfstrings don't go through that.
16253  if (!FD->hasAttr<FormatArgAttr>())
16254  FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16255  FD->getLocation()));
16256  }
16257 }
16258 
16260  TypeSourceInfo *TInfo) {
16261  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16262  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16263 
16264  if (!TInfo) {
16265  assert(D.isInvalidType() && "no declarator info for valid type");
16266  TInfo = Context.getTrivialTypeSourceInfo(T);
16267  }
16268 
16269  // Scope manipulation handled by caller.
16270  TypedefDecl *NewTD =
16271  TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
16272  D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16273 
16274  // Bail out immediately if we have an invalid declaration.
16275  if (D.isInvalidType()) {
16276  NewTD->setInvalidDecl();
16277  return NewTD;
16278  }
16279 
16281  if (CurContext->isFunctionOrMethod())
16282  Diag(NewTD->getLocation(), diag::err_module_private_local)
16283  << 2 << NewTD
16287  else
16288  NewTD->setModulePrivate();
16289  }
16290 
16291  // C++ [dcl.typedef]p8:
16292  // If the typedef declaration defines an unnamed class (or
16293  // enum), the first typedef-name declared by the declaration
16294  // to be that class type (or enum type) is used to denote the
16295  // class type (or enum type) for linkage purposes only.
16296  // We need to check whether the type was declared in the declaration.
16297  switch (D.getDeclSpec().getTypeSpecType()) {
16298  case TST_enum:
16299  case TST_struct:
16300  case TST_interface:
16301  case TST_union:
16302  case TST_class: {
16303  TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16304  setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16305  break;
16306  }
16307 
16308  default:
16309  break;
16310  }
16311 
16312  return NewTD;
16313 }
16314 
16315 /// Check that this is a valid underlying type for an enum declaration.
16317  SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16318  QualType T = TI->getType();
16319 
16320  if (T->isDependentType())
16321  return false;
16322 
16323  // This doesn't use 'isIntegralType' despite the error message mentioning
16324  // integral type because isIntegralType would also allow enum types in C.
16325  if (const BuiltinType *BT = T->getAs<BuiltinType>())
16326  if (BT->isInteger())
16327  return false;
16328 
16329  if (T->isBitIntType())
16330  return false;
16331 
16332  return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
16333 }
16334 
16335 /// Check whether this is a valid redeclaration of a previous enumeration.
16336 /// \return true if the redeclaration was invalid.
16337 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
16338  QualType EnumUnderlyingTy, bool IsFixed,
16339  const EnumDecl *Prev) {
16340  if (IsScoped != Prev->isScoped()) {
16341  Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16342  << Prev->isScoped();
16343  Diag(Prev->getLocation(), diag::note_previous_declaration);
16344  return true;
16345  }
16346 
16347  if (IsFixed && Prev->isFixed()) {
16348  if (!EnumUnderlyingTy->isDependentType() &&
16349  !Prev->getIntegerType()->isDependentType() &&
16350  !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
16351  Prev->getIntegerType())) {
16352  // TODO: Highlight the underlying type of the redeclaration.
16353  Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16354  << EnumUnderlyingTy << Prev->getIntegerType();
16355  Diag(Prev->getLocation(), diag::note_previous_declaration)
16356  << Prev->getIntegerTypeRange();
16357  return true;
16358  }
16359  } else if (IsFixed != Prev->isFixed()) {
16360  Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16361  << Prev->isFixed();
16362  Diag(Prev->getLocation(), diag::note_previous_declaration);
16363  return true;
16364  }
16365 
16366  return false;
16367 }
16368 
16369 /// Get diagnostic %select index for tag kind for
16370 /// redeclaration diagnostic message.
16371 /// WARNING: Indexes apply to particular diagnostics only!
16372 ///
16373 /// \returns diagnostic %select index.
16375  switch (Tag) {
16376  case TTK_Struct: return 0;
16377  case TTK_Interface: return 1;
16378  case TTK_Class: return 2;
16379  default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16380  }
16381 }
16382 
16383 /// Determine if tag kind is a class-key compatible with
16384 /// class for redeclaration (class, struct, or __interface).
16385 ///
16386 /// \returns true iff the tag kind is compatible.
16388 {
16389  return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
16390 }
16391 
16393  TagTypeKind TTK) {
16394  if (isa<TypedefDecl>(PrevDecl))
16395  return NTK_Typedef;
16396  else if (isa<TypeAliasDecl>(PrevDecl))
16397  return NTK_TypeAlias;
16398  else if (isa<ClassTemplateDecl>(PrevDecl))
16399  return NTK_Template;
16400  else if (isa<TypeAliasTemplateDecl>(PrevDecl))
16401  return NTK_TypeAliasTemplate;
16402  else if (isa<TemplateTemplateParmDecl>(PrevDecl))
16403  return NTK_TemplateTemplateArgument;
16404  switch (TTK) {
16405  case TTK_Struct:
16406  case TTK_Interface:
16407  case TTK_Class:
16408  return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
16409  case TTK_Union:
16410  return NTK_NonUnion;
16411  case TTK_Enum:
16412  return NTK_NonEnum;
16413  }
16414  llvm_unreachable("invalid TTK");
16415 }
16416 
16417 /// Determine whether a tag with a given kind is acceptable
16418 /// as a redeclaration of the given tag declaration.
16419 ///
16420 /// \returns true if the new tag kind is acceptable, false otherwise.
16422  TagTypeKind NewTag, bool isDefinition,
16423  SourceLocation NewTagLoc,
16424  const IdentifierInfo *Name) {
16425  // C++ [dcl.type.elab]p3:
16426  // The class-key or enum keyword present in the
16427  // elaborated-type-specifier shall agree in kind with the
16428  // declaration to which the name in the elaborated-type-specifier
16429  // refers. This rule also applies to the form of
16430  // elaborated-type-specifier that declares a class-name or
16431  // friend class since it can be construed as referring to the
16432  // definition of the class. Thus, in any
16433  // elaborated-type-specifier, the enum keyword shall be used to
16434  // refer to an enumeration (7.2), the union class-key shall be
16435  // used to refer to a union (clause 9), and either the class or
16436  // struct class-key shall be used to refer to a class (clause 9)
16437  // declared using the class or struct class-key.
16438  TagTypeKind OldTag = Previous->getTagKind();
16439  if (OldTag != NewTag &&
16440  !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
16441  return false;
16442 
16443  // Tags are compatible, but we might still want to warn on mismatched tags.
16444  // Non-class tags can't be mismatched at this point.
16445  if (!isClassCompatTagKind(NewTag))
16446  return true;
16447 
16448  // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16449  // by our warning analysis. We don't want to warn about mismatches with (eg)
16450  // declarations in system headers that are designed to be specialized, but if
16451  // a user asks us to warn, we should warn if their code contains mismatched
16452  // declarations.
16453  auto IsIgnoredLoc = [&](SourceLocation Loc) {
16454  return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
16455  Loc);
16456  };
16457  if (IsIgnoredLoc(NewTagLoc))
16458  return true;
16459 
16460  auto IsIgnored = [&](const TagDecl *Tag) {
16461  return IsIgnoredLoc(Tag->getLocation());
16462  };
16463  while (IsIgnored(Previous)) {
16464  Previous = Previous->getPreviousDecl();
16465  if (!Previous)
16466  return true;
16467  OldTag = Previous->getTagKind();
16468  }
16469 
16470  bool isTemplate = false;
16471  if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
16472  isTemplate = Record->getDescribedClassTemplate();
16473 
16474  if (inTemplateInstantiation()) {
16475  if (OldTag != NewTag) {
16476  // In a template instantiation, do not offer fix-its for tag mismatches
16477  // since they usually mess up the template instead of fixing the problem.
16478  Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16479  << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16480  << getRedeclDiagFromTagKind(OldTag);
16481  // FIXME: Note previous location?
16482  }
16483  return true;
16484  }
16485 
16486  if (isDefinition) {
16487  // On definitions, check all previous tags and issue a fix-it for each
16488  // one that doesn't match the current tag.
16489  if (Previous->getDefinition()) {
16490  // Don't suggest fix-its for redefinitions.
16491  return true;
16492  }
16493 
16494  bool previousMismatch = false;
16495  for (const TagDecl *I : Previous->redecls()) {
16496  if (I->getTagKind() != NewTag) {
16497  // Ignore previous declarations for which the warning was disabled.
16498  if (IsIgnored(I))
16499  continue;
16500 
16501  if (!previousMismatch) {
16502  previousMismatch = true;
16503  Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
16504  << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16505  << getRedeclDiagFromTagKind(I->getTagKind());
16506  }
16507  Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
16508  << getRedeclDiagFromTagKind(NewTag)
16509  << FixItHint::CreateReplacement(I->getInnerLocStart(),
16511  }
16512  }
16513  return true;
16514  }
16515 
16516  // Identify the prevailing tag kind: this is the kind of the definition (if
16517  // there is a non-ignored definition), or otherwise the kind of the prior
16518  // (non-ignored) declaration.
16519  const TagDecl *PrevDef = Previous->getDefinition();
16520  if (PrevDef && IsIgnored(PrevDef))
16521  PrevDef = nullptr;
16522  const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
16523  if (Redecl->getTagKind() != NewTag) {
16524  Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16525  << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16526  << getRedeclDiagFromTagKind(OldTag);
16527  Diag(Redecl->getLocation(), diag::note_previous_use);
16528 
16529  // If there is a previous definition, suggest a fix-it.
16530  if (PrevDef) {
16531  Diag(NewTagLoc, diag::note_struct_class_suggestion)
16532  << getRedeclDiagFromTagKind(Redecl->getTagKind())
16535  }
16536  }
16537 
16538  return true;
16539 }
16540 
16541 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
16542 /// from an outer enclosing namespace or file scope inside a friend declaration.
16543 /// This should provide the commented out code in the following snippet:
16544 /// namespace N {
16545 /// struct X;
16546 /// namespace M {
16547 /// struct Y { friend struct /*N::*/ X; };
16548 /// }
16549 /// }
16551  SourceLocation NameLoc) {
16552  // While the decl is in a namespace, do repeated lookup of that name and see
16553  // if we get the same namespace back. If we do not, continue until
16554  // translation unit scope, at which point we have a fully qualified NNS.
16557  for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
16558  // This tag should be declared in a namespace, which can only be enclosed by
16559  // other namespaces. Bail if there's an anonymous namespace in the chain.
16560  NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
16561  if (!Namespace || Namespace->isAnonymousNamespace())
16562  return FixItHint();
16563  IdentifierInfo *II = Namespace->getIdentifier();
16564  Namespaces.push_back(II);
16565  NamedDecl *Lookup = SemaRef.LookupSingleName(
16566  S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
16567  if (Lookup == Namespace)
16568  break;
16569  }
16570 
16571  // Once we have all the namespaces, reverse them to go outermost first, and
16572  // build an NNS.
16573  SmallString<64> Insertion;
16574  llvm::raw_svector_ostream OS(Insertion);
16575  if (DC->isTranslationUnit())
16576  OS << "::";
16577  std::reverse(Namespaces.begin(), Namespaces.end());
16578  for (auto *II : Namespaces)
16579  OS << II->getName() << "::";
16580  return FixItHint::CreateInsertion(NameLoc, Insertion);
16581 }
16582 
16583 /// Determine whether a tag originally declared in context \p OldDC can
16584 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
16585 /// found a declaration in \p OldDC as a previous decl, perhaps through a
16586 /// using-declaration).
16588  DeclContext *NewDC) {
16589  OldDC = OldDC->getRedeclContext();
16590  NewDC = NewDC->getRedeclContext();
16591 
16592  if (OldDC->Equals(NewDC))
16593  return true;
16594 
16595  // In MSVC mode, we allow a redeclaration if the contexts are related (either
16596  // encloses the other).
16597  if (S.getLangOpts().MSVCCompat &&
16598  (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
16599  return true;
16600 
16601  return false;
16602 }
16603 
16604 /// This is invoked when we see 'struct foo' or 'struct {'. In the
16605 /// former case, Name will be non-null. In the later case, Name will be null.
16606 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
16607 /// reference/declaration/definition of a tag.
16608 ///
16609 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
16610 /// trailing-type-specifier) other than one in an alias-declaration.
16611 ///
16612 /// \param SkipBody If non-null, will be set to indicate if the caller should
16613 /// skip the definition of this tag and treat it as if it were a declaration.
16614 DeclResult
16615 Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
16616  CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
16617  const ParsedAttributesView &Attrs, AccessSpecifier AS,
16618  SourceLocation ModulePrivateLoc,
16619  MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
16620  bool &IsDependent, SourceLocation ScopedEnumKWLoc,
16621  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
16622  bool IsTypeSpecifier, bool IsTemplateParamOrArg,
16623  OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
16624  // If this is not a definition, it must have a name.
16625  IdentifierInfo *OrigName = Name;
16626  assert((Name != nullptr || TUK == TUK_Definition) &&
16627  "Nameless record must be a definition!");
16628  assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
16629 
16630  OwnedDecl = false;
16632  bool ScopedEnum = ScopedEnumKWLoc.isValid();
16633 
16634  // FIXME: Check member specializations more carefully.
16635  bool isMemberSpecialization = false;
16636  bool Invalid = false;
16637 
16638  // We only need to do this matching if we have template parameters
16639  // or a scope specifier, which also conveniently avoids this work
16640  // for non-C++ cases.
16641  if (TemplateParameterLists.size() > 0 ||
16642  (SS.isNotEmpty() && TUK != TUK_Reference)) {
16643  if (TemplateParameterList *TemplateParams =
16644  MatchTemplateParametersToScopeSpecifier(
16645  KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
16646  TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
16647  if (Kind == TTK_Enum) {
16648  Diag(KWLoc, diag::err_enum_template);
16649  return true;
16650  }
16651 
16652  if (TemplateParams->size() > 0) {
16653  // This is a declaration or definition of a class template (which may
16654  // be a member of another template).
16655 
16656  if (Invalid)
16657  return true;
16658 
16659  OwnedDecl = false;
16660  DeclResult Result = CheckClassTemplate(
16661  S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
16662  AS, ModulePrivateLoc,
16663  /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
16664  TemplateParameterLists.data(), SkipBody);
16665  return Result.get();
16666  } else {
16667  // The "template<>" header is extraneous.
16668  Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16670  isMemberSpecialization = true;
16671  }
16672  }
16673 
16674  if (!TemplateParameterLists.empty() && isMemberSpecialization &&
16675  CheckTemplateDeclScope(S, TemplateParameterLists.back()))
16676  return true;
16677  }
16678 
16679  // Figure out the underlying type if this a enum declaration. We need to do
16680  // this early, because it's needed to detect if this is an incompatible
16681  // redeclaration.
16682  llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
16683  bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
16684 
16685  if (Kind == TTK_Enum) {
16686  if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
16687  // No underlying type explicitly specified, or we failed to parse the
16688  // type, default to int.
16689  EnumUnderlying = Context.IntTy.getTypePtr();
16690  } else if (UnderlyingType.get()) {
16691  // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16692  // integral type; any cv-qualification is ignored.
16693  TypeSourceInfo *TI = nullptr;
16694  GetTypeFromParser(UnderlyingType.get(), &TI);
16695  EnumUnderlying = TI;
16696 
16697  if (CheckEnumUnderlyingType(TI))
16698  // Recover by falling back to int.
16699  EnumUnderlying = Context.IntTy.getTypePtr();
16700 
16701  if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
16702  UPPC_FixedUnderlyingType))
16703  EnumUnderlying = Context.IntTy.getTypePtr();
16704 
16705  } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16706  // For MSVC ABI compatibility, unfixed enums must use an underlying type
16707  // of 'int'. However, if this is an unfixed forward declaration, don't set
16708  // the underlying type unless the user enables -fms-compatibility. This
16709  // makes unfixed forward declared enums incomplete and is more conforming.
16710  if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
16711  EnumUnderlying = Context.IntTy.getTypePtr();
16712  }
16713  }
16714 
16715  DeclContext *SearchDC = CurContext;
16716  DeclContext *DC = CurContext;
16717  bool isStdBadAlloc = false;
16718  bool isStdAlignValT = false;
16719 
16720  RedeclarationKind Redecl = forRedeclarationInCurContext();
16721  if (TUK == TUK_Friend || TUK == TUK_Reference)
16722  Redecl = NotForRedeclaration;
16723 
16724  /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16725  /// implemented asks for structural equivalence checking, the returned decl
16726  /// here is passed back to the parser, allowing the tag body to be parsed.
16727  auto createTagFromNewDecl = [&]() -> TagDecl * {
16728  assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
16729  // If there is an identifier, use the location of the identifier as the
16730  // location of the decl, otherwise use the location of the struct/union
16731  // keyword.
16732  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16733  TagDecl *New = nullptr;
16734 
16735  if (Kind == TTK_Enum) {
16736  New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
16737  ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
16738  // If this is an undefined enum, bail.
16739  if (TUK != TUK_Definition && !Invalid)
16740  return nullptr;
16741  if (EnumUnderlying) {
16742  EnumDecl *ED = cast<EnumDecl>(New);
16743  if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
16744  ED->setIntegerTypeSourceInfo(TI);
16745  else
16746  ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16747  QualType EnumTy = ED->getIntegerType();
16748  ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
16749  ? Context.getPromotedIntegerType(EnumTy)
16750  : EnumTy);
16751  }
16752  } else { // struct/union
16753  New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16754  nullptr);
16755  }
16756 
16757  if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16758  // Add alignment attributes if necessary; these attributes are checked
16759  // when the ASTContext lays out the structure.
16760  //
16761  // It is important for implementing the correct semantics that this
16762  // happen here (in ActOnTag). The #pragma pack stack is
16763  // maintained as a result of parser callbacks which can occur at
16764  // many points during the parsing of a struct declaration (because
16765  // the #pragma tokens are effectively skipped over during the
16766  // parsing of the struct).
16767  if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16768  AddAlignmentAttributesForRecord(RD);
16769  AddMsStructLayoutForRecord(RD);
16770  }
16771  }
16772  New->setLexicalDeclContext(CurContext);
16773  return New;
16774  };
16775 
16776  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
16777  if (Name && SS.isNotEmpty()) {
16778  // We have a nested-name tag ('struct foo::bar').
16779 
16780  // Check for invalid 'foo::'.
16781  if (SS.isInvalid()) {
16782  Name = nullptr;
16783  goto CreateNewDecl;
16784  }
16785 
16786  // If this is a friend or a reference to a class in a dependent
16787  // context, don't try to make a decl for it.
16788  if (TUK == TUK_Friend || TUK == TUK_Reference) {
16789  DC = computeDeclContext(SS, false);
16790  if (!DC) {
16791  IsDependent = true;
16792  return true;
16793  }
16794  } else {
16795  DC = computeDeclContext(SS, true);
16796  if (!DC) {
16797  Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
16798  << SS.getRange();
16799  return true;
16800  }
16801  }
16802 
16803  if (RequireCompleteDeclContext(SS, DC))
16804  return true;
16805 
16806  SearchDC = DC;
16807  // Look-up name inside 'foo::'.
16808  LookupQualifiedName(Previous, DC);
16809 
16810  if (Previous.isAmbiguous())
16811  return true;
16812 
16813  if (Previous.empty()) {
16814  // Name lookup did not find anything. However, if the
16815  // nested-name-specifier refers to the current instantiation,
16816  // and that current instantiation has any dependent base
16817  // classes, we might find something at instantiation time: treat
16818  // this as a dependent elaborated-type-specifier.
16819  // But this only makes any sense for reference-like lookups.
16820  if (Previous.wasNotFoundInCurrentInstantiation() &&
16821  (TUK == TUK_Reference || TUK == TUK_Friend)) {
16822  IsDependent = true;
16823  return true;
16824  }
16825 
16826  // A tag 'foo::bar' must already exist.
16827  Diag(NameLoc, diag::err_not_tag_in_scope)
16828  << Kind << Name << DC << SS.getRange();
16829  Name = nullptr;
16830  Invalid = true;
16831  goto CreateNewDecl;
16832  }
16833  } else if (Name) {
16834  // C++14 [class.mem]p14:
16835  // If T is the name of a class, then each of the following shall have a
16836  // name different from T:
16837  // -- every member of class T that is itself a type
16838  if (TUK != TUK_Reference && TUK != TUK_Friend &&
16839  DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16840  return true;
16841 
16842  // If this is a named struct, check to see if there was a previous forward
16843  // declaration or definition.
16844  // FIXME: We're looking into outer scopes here, even when we
16845  // shouldn't be. Doing so can result in ambiguities that we
16846  // shouldn't be diagnosing.
16847  LookupName(Previous, S);
16848 
16849  // When declaring or defining a tag, ignore ambiguities introduced
16850  // by types using'ed into this scope.
16851  if (Previous.isAmbiguous() &&
16852  (TUK == TUK_Definition || TUK == TUK_Declaration)) {
16853  LookupResult::Filter F = Previous.makeFilter();
16854  while (F.hasNext()) {
16855  NamedDecl *ND = F.next();
16856  if (!ND->getDeclContext()->getRedeclContext()->Equals(
16857  SearchDC->getRedeclContext()))
16858  F.erase();
16859  }
16860  F.done();
16861  }
16862 
16863  // C++11 [namespace.memdef]p3:
16864  // If the name in a friend declaration is neither qualified nor
16865  // a template-id and the declaration is a function or an
16866  // elaborated-type-specifier, the lookup to determine whether
16867  // the entity has been previously declared shall not consider
16868  // any scopes outside the innermost enclosing namespace.
16869  //
16870  // MSVC doesn't implement the above rule for types, so a friend tag
16871  // declaration may be a redeclaration of a type declared in an enclosing
16872  // scope. They do implement this rule for friend functions.
16873  //
16874  // Does it matter that this should be by scope instead of by
16875  // semantic context?
16876  if (!Previous.empty() && TUK == TUK_Friend) {
16877  DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16878  LookupResult::Filter F = Previous.makeFilter();
16879  bool FriendSawTagOutsideEnclosingNamespace = false;
16880  while (F.hasNext()) {
16881  NamedDecl *ND = F.next();
16883  if (DC->isFileContext() &&
16884  !EnclosingNS->Encloses(ND->getDeclContext())) {
16885  if (getLangOpts().MSVCCompat)
16886  FriendSawTagOutsideEnclosingNamespace = true;
16887  else
16888  F.erase();
16889  }
16890  }
16891  F.done();
16892 
16893  // Diagnose this MSVC extension in the easy case where lookup would have
16894  // unambiguously found something outside the enclosing namespace.
16895  if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16896  NamedDecl *ND = Previous.getFoundDecl();
16897  Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16898  << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16899  }
16900  }
16901 
16902  // Note: there used to be some attempt at recovery here.
16903  if (Previous.isAmbiguous())
16904  return true;
16905 
16906  if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16907  // FIXME: This makes sure that we ignore the contexts associated
16908  // with C structs, unions, and enums when looking for a matching
16909  // tag declaration or definition. See the similar lookup tweak
16910  // in Sema::LookupName; is there a better way to deal with this?
16911  while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
16912  SearchDC = SearchDC->getParent();
16913  } else if (getLangOpts().CPlusPlus) {
16914  // Inside ObjCContainer want to keep it as a lexical decl context but go
16915  // past it (most often to TranslationUnit) to find the semantic decl
16916  // context.
16917  while (isa<ObjCContainerDecl>(SearchDC))
16918  SearchDC = SearchDC->getParent();
16919  }
16920  } else if (getLangOpts().CPlusPlus) {
16921  // Don't use ObjCContainerDecl as the semantic decl context for anonymous
16922  // TagDecl the same way as we skip it for named TagDecl.
16923  while (isa<ObjCContainerDecl>(SearchDC))
16924  SearchDC = SearchDC->getParent();
16925  }
16926 
16927  if (Previous.isSingleResult() &&
16928  Previous.getFoundDecl()->isTemplateParameter()) {
16929  // Maybe we will complain about the shadowed template parameter.
16930  DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16931  // Just pretend that we didn't see the previous declaration.
16932  Previous.clear();
16933  }
16934 
16935  if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16936  DC->Equals(getStdNamespace())) {
16937  if (Name->isStr("bad_alloc")) {
16938  // This is a declaration of or a reference to "std::bad_alloc".
16939  isStdBadAlloc = true;
16940 
16941  // If std::bad_alloc has been implicitly declared (but made invisible to
16942  // name lookup), fill in this implicit declaration as the previous
16943  // declaration, so that the declarations get chained appropriately.
16944  if (Previous.empty() && StdBadAlloc)
16945  Previous.addDecl(getStdBadAlloc());
16946  } else if (Name->isStr("align_val_t")) {
16947  isStdAlignValT = true;
16948  if (Previous.empty() && StdAlignValT)
16949  Previous.addDecl(getStdAlignValT());
16950  }
16951  }
16952 
16953  // If we didn't find a previous declaration, and this is a reference
16954  // (or friend reference), move to the correct scope. In C++, we
16955  // also need to do a redeclaration lookup there, just in case
16956  // there's a shadow friend decl.
16957  if (Name && Previous.empty() &&
16958  (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16959  if (Invalid) goto CreateNewDecl;
16960  assert(SS.isEmpty());
16961 
16962  if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16963  // C++ [basic.scope.pdecl]p5:
16964  // -- for an elaborated-type-specifier of the form
16965  //
16966  // class-key identifier
16967  //
16968  // if the elaborated-type-specifier is used in the
16969  // decl-specifier-seq or parameter-declaration-clause of a
16970  // function defined in namespace scope, the identifier is
16971  // declared as a class-name in the namespace that contains
16972  // the declaration; otherwise, except as a friend
16973  // declaration, the identifier is declared in the smallest
16974  // non-class, non-function-prototype scope that contains the
16975  // declaration.
16976  //
16977  // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16978  // C structs and unions.
16979  //
16980  // It is an error in C++ to declare (rather than define) an enum
16981  // type, including via an elaborated type specifier. We'll
16982  // diagnose that later; for now, declare the enum in the same
16983  // scope as we would have picked for any other tag type.
16984  //
16985  // GNU C also supports this behavior as part of its incomplete
16986  // enum types extension, while GNU C++ does not.
16987  //
16988  // Find the context where we'll be declaring the tag.
16989  // FIXME: We would like to maintain the current DeclContext as the
16990  // lexical context,
16991  SearchDC = getTagInjectionContext(SearchDC);
16992 
16993  // Find the scope where we'll be declaring the tag.
16994  S = getTagInjectionScope(S, getLangOpts());
16995  } else {
16996  assert(TUK == TUK_Friend);
16997  // C++ [namespace.memdef]p3:
16998  // If a friend declaration in a non-local class first declares a
16999  // class or function, the friend class or function is a member of
17000  // the innermost enclosing namespace.
17001  SearchDC = SearchDC->getEnclosingNamespaceContext();
17002  }
17003 
17004  // In C++, we need to do a redeclaration lookup to properly
17005  // diagnose some problems.
17006  // FIXME: redeclaration lookup is also used (with and without C++) to find a
17007  // hidden declaration so that we don't get ambiguity errors when using a
17008  // type declared by an elaborated-type-specifier. In C that is not correct
17009  // and we should instead merge compatible types found by lookup.
17010  if (getLangOpts().CPlusPlus) {
17011  // FIXME: This can perform qualified lookups into function contexts,
17012  // which are meaningless.
17013  Previous.setRedeclarationKind(forRedeclarationInCurContext());
17014  LookupQualifiedName(Previous, SearchDC);
17015  } else {
17016  Previous.setRedeclarationKind(forRedeclarationInCurContext());
17017  LookupName(Previous, S);
17018  }
17019  }
17020 
17021  // If we have a known previous declaration to use, then use it.
17022  if (Previous.empty() && SkipBody && SkipBody->Previous)
17023  Previous.addDecl(SkipBody->Previous);
17024 
17025  if (!Previous.empty()) {
17026  NamedDecl *PrevDecl = Previous.getFoundDecl();
17027  NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17028 
17029  // It's okay to have a tag decl in the same scope as a typedef
17030  // which hides a tag decl in the same scope. Finding this
17031  // with a redeclaration lookup can only actually happen in C++.
17032  //
17033  // This is also okay for elaborated-type-specifiers, which is
17034  // technically forbidden by the current standard but which is
17035  // okay according to the likely resolution of an open issue;
17036  // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17037  if (getLangOpts().CPlusPlus) {
17038  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17039  if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17040  TagDecl *Tag = TT->getDecl();
17041  if (Tag->getDeclName() == Name &&
17043  ->Equals(TD->getDeclContext()->getRedeclContext())) {
17044  PrevDecl = Tag;
17045  Previous.clear();
17046  Previous.addDecl(Tag);
17047  Previous.resolveKind();
17048  }
17049  }
17050  }
17051  }
17052 
17053  // If this is a redeclaration of a using shadow declaration, it must
17054  // declare a tag in the same context. In MSVC mode, we allow a
17055  // redefinition if either context is within the other.
17056  if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17057  auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17058  if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
17059  isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17060  !(OldTag && isAcceptableTagRedeclContext(
17061  *this, OldTag->getDeclContext(), SearchDC))) {
17062  Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17063  Diag(Shadow->getTargetDecl()->getLocation(),
17064  diag::note_using_decl_target);
17065  Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17066  << 0;
17067  // Recover by ignoring the old declaration.
17068  Previous.clear();
17069  goto CreateNewDecl;
17070  }
17071  }
17072 
17073  if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17074  // If this is a use of a previous tag, or if the tag is already declared
17075  // in the same scope (so that the definition/declaration completes or
17076  // rementions the tag), reuse the decl.
17077  if (TUK == TUK_Reference || TUK == TUK_Friend ||
17078  isDeclInScope(DirectPrevDecl, SearchDC, S,
17079  SS.isNotEmpty() || isMemberSpecialization)) {
17080  // Make sure that this wasn't declared as an enum and now used as a
17081  // struct or something similar.
17082  if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17083  TUK == TUK_Definition, KWLoc,
17084  Name)) {
17085  bool SafeToContinue
17086  = (PrevTagDecl->getTagKind() != TTK_Enum &&
17087  Kind != TTK_Enum);
17088  if (SafeToContinue)
17089  Diag(KWLoc, diag::err_use_with_wrong_tag)
17090  << Name
17092  PrevTagDecl->getKindName());
17093  else
17094  Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17095  Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17096 
17097  if (SafeToContinue)
17098  Kind = PrevTagDecl->getTagKind();
17099  else {
17100  // Recover by making this an anonymous redefinition.
17101  Name = nullptr;
17102  Previous.clear();
17103  Invalid = true;
17104  }
17105  }
17106 
17107  if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
17108  const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17109  if (TUK == TUK_Reference || TUK == TUK_Friend)
17110  return PrevTagDecl;
17111 
17112  QualType EnumUnderlyingTy;
17113  if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17114  EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17115  else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17116  EnumUnderlyingTy = QualType(T, 0);
17117 
17118  // All conflicts with previous declarations are recovered by
17119  // returning the previous declaration, unless this is a definition,
17120  // in which case we want the caller to bail out.
17121  if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17122  ScopedEnum, EnumUnderlyingTy,
17123  IsFixed, PrevEnum))
17124  return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
17125  }
17126 
17127  // C++11 [class.mem]p1:
17128  // A member shall not be declared twice in the member-specification,
17129  // except that a nested class or member class template can be declared
17130  // and then later defined.
17131  if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
17132  S->isDeclScope(PrevDecl)) {
17133  Diag(NameLoc, diag::ext_member_redeclared);
17134  Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17135  }
17136 
17137  if (!Invalid) {
17138  // If this is a use, just return the declaration we found, unless
17139  // we have attributes.
17140  if (TUK == TUK_Reference || TUK == TUK_Friend) {
17141  if (!Attrs.empty()) {
17142  // FIXME: Diagnose these attributes. For now, we create a new
17143  // declaration to hold them.
17144  } else if (TUK == TUK_Reference &&
17145  (PrevTagDecl->getFriendObjectKind() ==
17147  PrevDecl->getOwningModule() != getCurrentModule()) &&
17148  SS.isEmpty()) {
17149  // This declaration is a reference to an existing entity, but
17150  // has different visibility from that entity: it either makes
17151  // a friend visible or it makes a type visible in a new module.
17152  // In either case, create a new declaration. We only do this if
17153  // the declaration would have meant the same thing if no prior
17154  // declaration were found, that is, if it was found in the same
17155  // scope where we would have injected a declaration.
17156  if (!getTagInjectionContext(CurContext)->getRedeclContext()
17157  ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17158  return PrevTagDecl;
17159  // This is in the injected scope, create a new declaration in
17160  // that scope.
17161  S = getTagInjectionScope(S, getLangOpts());
17162  } else {
17163  return PrevTagDecl;
17164  }
17165  }
17166 
17167  // Diagnose attempts to redefine a tag.
17168  if (TUK == TUK_Definition) {
17169  if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17170  // If we're defining a specialization and the previous definition
17171  // is from an implicit instantiation, don't emit an error
17172  // here; we'll catch this in the general case below.
17173  bool IsExplicitSpecializationAfterInstantiation = false;
17174  if (isMemberSpecialization) {
17175  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17176  IsExplicitSpecializationAfterInstantiation =
17177  RD->getTemplateSpecializationKind() !=
17179  else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17180  IsExplicitSpecializationAfterInstantiation =
17181  ED->getTemplateSpecializationKind() !=
17183  }
17184 
17185  // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17186  // not keep more that one definition around (merge them). However,
17187  // ensure the decl passes the structural compatibility check in
17188  // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17189  NamedDecl *Hidden = nullptr;
17190  if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17191  // There is a definition of this tag, but it is not visible. We
17192  // explicitly make use of C++'s one definition rule here, and
17193  // assume that this definition is identical to the hidden one
17194  // we already have. Make the existing definition visible and
17195  // use it in place of this one.
17196  if (!getLangOpts().CPlusPlus) {
17197  // Postpone making the old definition visible until after we
17198  // complete parsing the new one and do the structural
17199  // comparison.
17200  SkipBody->CheckSameAsPrevious = true;
17201  SkipBody->New = createTagFromNewDecl();
17202  SkipBody->Previous = Def;
17203  return Def;
17204  } else {
17205  SkipBody->ShouldSkip = true;
17206  SkipBody->Previous = Def;
17207  makeMergedDefinitionVisible(Hidden);
17208  // Carry on and handle it like a normal definition. We'll
17209  // skip starting the definitiion later.
17210  }
17211  } else if (!IsExplicitSpecializationAfterInstantiation) {
17212  // A redeclaration in function prototype scope in C isn't
17213  // visible elsewhere, so merely issue a warning.
17214  if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17215  Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17216  else
17217  Diag(NameLoc, diag::err_redefinition) << Name;
17218  notePreviousDefinition(Def,
17219  NameLoc.isValid() ? NameLoc : KWLoc);
17220  // If this is a redefinition, recover by making this
17221  // struct be anonymous, which will make any later
17222  // references get the previous definition.
17223  Name = nullptr;
17224  Previous.clear();
17225  Invalid = true;
17226  }
17227  } else {
17228  // If the type is currently being defined, complain
17229  // about a nested redefinition.
17230  auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17231  if (TD->isBeingDefined()) {
17232  Diag(NameLoc, diag::err_nested_redefinition) << Name;
17233  Diag(PrevTagDecl->getLocation(),
17234  diag::note_previous_definition);
17235  Name = nullptr;
17236  Previous.clear();
17237  Invalid = true;
17238  }
17239  }
17240 
17241  // Okay, this is definition of a previously declared or referenced
17242  // tag. We're going to create a new Decl for it.
17243  }
17244 
17245  // Okay, we're going to make a redeclaration. If this is some kind
17246  // of reference, make sure we build the redeclaration in the same DC
17247  // as the original, and ignore the current access specifier.
17248  if (TUK == TUK_Friend || TUK == TUK_Reference) {
17249  SearchDC = PrevTagDecl->getDeclContext();
17250  AS = AS_none;
17251  }
17252  }
17253  // If we get here we have (another) forward declaration or we
17254  // have a definition. Just create a new decl.
17255 
17256  } else {
17257  // If we get here, this is a definition of a new tag type in a nested
17258  // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17259  // new decl/type. We set PrevDecl to NULL so that the entities
17260  // have distinct types.
17261  Previous.clear();
17262  }
17263  // If we get here, we're going to create a new Decl. If PrevDecl
17264  // is non-NULL, it's a definition of the tag declared by
17265  // PrevDecl. If it's NULL, we have a new definition.
17266 
17267  // Otherwise, PrevDecl is not a tag, but was found with tag
17268  // lookup. This is only actually possible in C++, where a few
17269  // things like templates still live in the tag namespace.
17270  } else {
17271  // Use a better diagnostic if an elaborated-type-specifier
17272  // found the wrong kind of type on the first
17273  // (non-redeclaration) lookup.
17274  if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
17275  !Previous.isForRedeclaration()) {
17276  NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17277  Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
17278  << Kind;
17279  Diag(PrevDecl->getLocation(), diag::note_declared_at);
17280  Invalid = true;
17281 
17282  // Otherwise, only diagnose if the declaration is in scope.
17283  } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17284  SS.isNotEmpty() || isMemberSpecialization)) {
17285  // do nothing
17286 
17287  // Diagnose implicit declarations introduced by elaborated types.
17288  } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
17289  NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17290  Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17291  Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17292  Invalid = true;
17293 
17294  // Otherwise it's a declaration. Call out a particularly common
17295  // case here.
17296  } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17297  unsigned Kind = 0;
17298  if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
17299  Diag(NameLoc, diag::err_tag_definition_of_typedef)
17300  << Name << Kind << TND->getUnderlyingType();
17301  Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17302  Invalid = true;
17303 
17304  // Otherwise, diagnose.
17305  } else {
17306  // The tag name clashes with something else in the target scope,
17307  // issue an error and recover by making this tag be anonymous.
17308  Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17309  notePreviousDefinition(PrevDecl, NameLoc);
17310  Name = nullptr;
17311  Invalid = true;
17312  }
17313 
17314  // The existing declaration isn't relevant to us; we're in a
17315  // new scope, so clear out the previous declaration.
17316  Previous.clear();
17317  }
17318  }
17319 
17320 CreateNewDecl:
17321 
17322  TagDecl *PrevDecl = nullptr;
17323  if (Previous.isSingleResult())
17324  PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
17325 
17326  // If there is an identifier, use the location of the identifier as the
17327  // location of the decl, otherwise use the location of the struct/union
17328  // keyword.
17329  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17330 
17331  // Otherwise, create a new declaration. If there is a previous
17332  // declaration of the same entity, the two will be linked via
17333  // PrevDecl.
17334  TagDecl *New;
17335 
17336  if (Kind == TTK_Enum) {
17337  // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17338  // enum X { A, B, C } D; D should chain to X.
17339  New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
17340  cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
17341  ScopedEnumUsesClassTag, IsFixed);
17342 
17343  if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
17344  StdAlignValT = cast<EnumDecl>(New);
17345 
17346  // If this is an undefined enum, warn.
17347  if (TUK != TUK_Definition && !Invalid) {
17348  TagDecl *Def;
17349  if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
17350  // C++0x: 7.2p2: opaque-enum-declaration.
17351  // Conflicts are diagnosed above. Do nothing.
17352  }
17353  else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
17354  Diag(Loc, diag::ext_forward_ref_enum_def)
17355  << New;
17356  Diag(Def->getLocation(), diag::note_previous_definition);
17357  } else {
17358  unsigned DiagID = diag::ext_forward_ref_enum;
17359  if (getLangOpts().MSVCCompat)
17360  DiagID = diag::ext_ms_forward_ref_enum;
17361  else if (getLangOpts().CPlusPlus)
17362  DiagID = diag::err_forward_ref_enum;
17363  Diag(Loc, DiagID);
17364  }
17365  }
17366 
17367  if (EnumUnderlying) {
17368  EnumDecl *ED = cast<EnumDecl>(New);
17369  if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17370  ED->setIntegerTypeSourceInfo(TI);
17371  else
17372  ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17373  QualType EnumTy = ED->getIntegerType();
17374  ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17375  ? Context.getPromotedIntegerType(EnumTy)
17376  : EnumTy);
17377  assert(ED->isComplete() && "enum with type should be complete");
17378  }
17379  } else {
17380  // struct/union/class
17381 
17382  // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17383  // struct X { int A; } D; D should chain to X.
17384  if (getLangOpts().CPlusPlus) {
17385  // FIXME: Look for a way to use RecordDecl for simple structs.
17386  New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17387  cast_or_null<CXXRecordDecl>(PrevDecl));
17388 
17389  if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
17390  StdBadAlloc = cast<CXXRecordDecl>(New);
17391  } else
17392  New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17393  cast_or_null<RecordDecl>(PrevDecl));
17394  }
17395 
17396  if (OOK != OOK_Outside && TUK == TUK_Definition && !getLangOpts().CPlusPlus)
17397  Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
17398  << (OOK == OOK_Macro) << New->getSourceRange();
17399 
17400  // C++11 [dcl.type]p3:
17401  // A type-specifier-seq shall not define a class or enumeration [...].
17402  if (!Invalid && getLangOpts().CPlusPlus &&
17403  (IsTypeSpecifier || IsTemplateParamOrArg) && TUK == TUK_Definition) {
17404  Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
17405  << Context.getTagDeclType(New);
17406  Invalid = true;
17407  }
17408 
17409  if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
17410  DC->getDeclKind() == Decl::Enum) {
17411  Diag(New->getLocation(), diag::err_type_defined_in_enum)
17412  << Context.getTagDeclType(New);
17413  Invalid = true;
17414  }
17415 
17416  // Maybe add qualifier info.
17417  if (SS.isNotEmpty()) {
17418  if (SS.isSet()) {
17419  // If this is either a declaration or a definition, check the
17420  // nested-name-specifier against the current context.
17421  if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
17422  diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
17423  isMemberSpecialization))
17424  Invalid = true;
17425 
17426  New->setQualifierInfo(SS.getWithLocInContext(Context));
17427  if (TemplateParameterLists.size() > 0) {
17428  New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
17429  }
17430  }
17431  else
17432  Invalid = true;
17433  }
17434 
17435  if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17436  // Add alignment attributes if necessary; these attributes are checked when
17437  // the ASTContext lays out the structure.
17438  //
17439  // It is important for implementing the correct semantics that this
17440  // happen here (in ActOnTag). The #pragma pack stack is
17441  // maintained as a result of parser callbacks which can occur at
17442  // many points during the parsing of a struct declaration (because
17443  // the #pragma tokens are effectively skipped over during the
17444  // parsing of the struct).
17445  if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17446  AddAlignmentAttributesForRecord(RD);
17447  AddMsStructLayoutForRecord(RD);
17448  }
17449  }
17450 
17451  if (ModulePrivateLoc.isValid()) {
17452  if (isMemberSpecialization)
17453  Diag(New->getLocation(), diag::err_module_private_specialization)
17454  << 2
17455  << FixItHint::CreateRemoval(ModulePrivateLoc);
17456  // __module_private__ does not apply to local classes. However, we only
17457  // diagnose this as an error when the declaration specifiers are
17458  // freestanding. Here, we just ignore the __module_private__.
17459  else if (!SearchDC->isFunctionOrMethod())
17460  New->setModulePrivate();
17461  }
17462 
17463  // If this is a specialization of a member class (of a class template),
17464  // check the specialization.
17465  if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
17466  Invalid = true;
17467 
17468  // If we're declaring or defining a tag in function prototype scope in C,
17469  // note that this type can only be used within the function and add it to
17470  // the list of decls to inject into the function definition scope.
17471  if ((Name || Kind == TTK_Enum) &&
17472  getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
17473  if (getLangOpts().CPlusPlus) {
17474  // C++ [dcl.fct]p6:
17475  // Types shall not be defined in return or parameter types.
17476  if (TUK == TUK_Definition && !IsTypeSpecifier) {
17477  Diag(Loc, diag::err_type_defined_in_param_type)
17478  << Name;
17479  Invalid = true;
17480  }
17481  } else if (!PrevDecl) {
17482  Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
17483  }
17484  }
17485 
17486  if (Invalid)
17487  New->setInvalidDecl();
17488 
17489  // Set the lexical context. If the tag has a C++ scope specifier, the
17490  // lexical context will be different from the semantic context.
17491  New->setLexicalDeclContext(CurContext);
17492 
17493  // Mark this as a friend decl if applicable.
17494  // In Microsoft mode, a friend declaration also acts as a forward
17495  // declaration so we always pass true to setObjectOfFriendDecl to make
17496  // the tag name visible.
17497  if (TUK == TUK_Friend)
17498  New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
17499 
17500  // Set the access specifier.
17501  if (!Invalid && SearchDC->isRecord())
17502  SetMemberAccessSpecifier(New, PrevDecl, AS);
17503 
17504  if (PrevDecl)
17505  CheckRedeclarationInModule(New, PrevDecl);
17506 
17507  if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
17508  New->startDefinition();
17509 
17510  ProcessDeclAttributeList(S, New, Attrs);
17511  AddPragmaAttributes(S, New);
17512 
17513  // If this has an identifier, add it to the scope stack.
17514  if (TUK == TUK_Friend) {
17515  // We might be replacing an existing declaration in the lookup tables;
17516  // if so, borrow its access specifier.
17517  if (PrevDecl)
17518  New->setAccess(PrevDecl->getAccess());
17519 
17521  DC->makeDeclVisibleInContext(New);
17522  if (Name) // can be null along some error paths
17523  if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17524  PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
17525  } else if (Name) {
17526  S = getNonFieldDeclScope(S);
17527  PushOnScopeChains(New, S, true);
17528  } else {
17529  CurContext->addDecl(New);
17530  }
17531 
17532  // If this is the C FILE type, notify the AST context.
17533  if (IdentifierInfo *II = New->getIdentifier())
17534  if (!New->isInvalidDecl() &&
17536  II->isStr("FILE"))
17537  Context.setFILEDecl(New);
17538 
17539  if (PrevDecl)
17540  mergeDeclAttributes(New, PrevDecl);
17541 
17542  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
17543  inferGslOwnerPointerAttribute(CXXRD);
17544 
17545  // If there's a #pragma GCC visibility in scope, set the visibility of this
17546  // record.
17547  AddPushedVisibilityAttribute(New);
17548 
17549  if (isMemberSpecialization && !New->isInvalidDecl())
17550  CompleteMemberSpecialization(New, Previous);
17551 
17552  OwnedDecl = true;
17553  // In C++, don't return an invalid declaration. We can't recover well from
17554  // the cases where we make the type anonymous.
17555  if (Invalid && getLangOpts().CPlusPlus) {
17556  if (New->isBeingDefined())
17557  if (auto RD = dyn_cast<RecordDecl>(New))
17558  RD->completeDefinition();
17559  return true;
17560  } else if (SkipBody && SkipBody->ShouldSkip) {
17561  return SkipBody->Previous;
17562  } else {
17563  return New;
17564  }
17565 }
17566 
17568  AdjustDeclIfTemplate(TagD);
17569  TagDecl *Tag = cast<TagDecl>(TagD);
17570 
17571  // Enter the tag context.
17572  PushDeclContext(S, Tag);
17573 
17574  ActOnDocumentableDecl(TagD);
17575 
17576  // If there's a #pragma GCC visibility in scope, set the visibility of this
17577  // record.
17578  AddPushedVisibilityAttribute(Tag);
17579 }
17580 
17582  if (!hasStructuralCompatLayout(Prev, SkipBody.New))
17583  return false;
17584 
17585  // Make the previous decl visible.
17586  makeMergedDefinitionVisible(SkipBody.Previous);
17587  return true;
17588 }
17589 
17591  assert(IDecl->getLexicalParent() == CurContext &&
17592  "The next DeclContext should be lexically contained in the current one.");
17593  CurContext = IDecl;
17594 }
17595 
17597  SourceLocation FinalLoc,
17598  bool IsFinalSpelledSealed,
17599  bool IsAbstract,
17600  SourceLocation LBraceLoc) {
17601  AdjustDeclIfTemplate(TagD);
17602  CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
17603 
17604  FieldCollector->StartClass();
17605 
17606  if (!Record->getIdentifier())
17607  return;
17608 
17609  if (IsAbstract)
17610  Record->markAbstract();
17611 
17612  if (FinalLoc.isValid()) {
17613  Record->addAttr(FinalAttr::Create(
17614  Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
17615  static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
17616  }
17617  // C++ [class]p2:
17618  // [...] The class-name is also inserted into the scope of the
17619  // class itself; this is known as the injected-class-name. For
17620  // purposes of access checking, the injected-class-name is treated
17621  // as if it were a public member name.
17622  CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
17623  Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
17624  Record->getLocation(), Record->getIdentifier(),
17625  /*PrevDecl=*/nullptr,
17626  /*DelayTypeCreation=*/true);
17627  Context.getTypeDeclType(InjectedClassName, Record);
17628  InjectedClassName->setImplicit();
17629  InjectedClassName->setAccess(AS_public);
17630  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
17631  InjectedClassName->setDescribedClassTemplate(Template);
17632  PushOnScopeChains(InjectedClassName, S);
17633  assert(InjectedClassName->isInjectedClassName() &&
17634  "Broken injected-class-name");
17635 }
17636 
17638  SourceRange BraceRange) {
17639  AdjustDeclIfTemplate(TagD);
17640  TagDecl *Tag = cast<TagDecl>(TagD);
17641  Tag->setBraceRange(BraceRange);
17642 
17643  // Make sure we "complete" the definition even it is invalid.
17644  if (Tag->isBeingDefined()) {
17645  assert(Tag->isInvalidDecl() && "We should already have completed it");
17646  if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17647  RD->completeDefinition();
17648  }
17649 
17650  if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
17651  FieldCollector->FinishClass();
17652  if (RD->hasAttr<SYCLSpecialClassAttr>()) {
17653  auto *Def = RD->getDefinition();
17654  assert(Def && "The record is expected to have a completed definition");
17655  unsigned NumInitMethods = 0;
17656  for (auto *Method : Def->methods()) {
17657  if (!Method->getIdentifier())
17658  continue;
17659  if (Method->getName() == "__init")
17660  NumInitMethods++;
17661  }
17662  if (NumInitMethods > 1 || !Def->hasInitMethod())
17663  Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
17664  }
17665  }
17666 
17667  // Exit this scope of this tag's definition.
17668  PopDeclContext();
17669 
17670  if (getCurLexicalContext()->isObjCContainer() &&
17671  Tag->getDeclContext()->isFileContext())
17673 
17674  // Notify the consumer that we've defined a tag.
17675  if (!Tag->isInvalidDecl())
17676  Consumer.HandleTagDeclDefinition(Tag);
17677 
17678  // Clangs implementation of #pragma align(packed) differs in bitfield layout
17679  // from XLs and instead matches the XL #pragma pack(1) behavior.
17680  if (Context.getTargetInfo().getTriple().isOSAIX() &&
17681  AlignPackStack.hasValue()) {
17682  AlignPackInfo APInfo = AlignPackStack.CurrentValue;
17683  // Only diagnose #pragma align(packed).
17684  if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
17685  return;
17686  const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
17687  if (!RD)
17688  return;
17689  // Only warn if there is at least 1 bitfield member.
17690  if (llvm::any_of(RD->fields(),
17691  [](const FieldDecl *FD) { return FD->isBitField(); }))
17692  Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
17693  }
17694 }
17695 
17697  // Exit this scope of this interface definition.
17698  PopDeclContext();
17699 }
17700 
17702  assert(ObjCCtx == CurContext && "Mismatch of container contexts");
17703  OriginalLexicalContext = ObjCCtx;
17704  ActOnObjCContainerFinishDefinition();
17705 }
17706 
17708  ActOnObjCContainerStartDefinition(ObjCCtx);
17709  OriginalLexicalContext = nullptr;
17710 }
17711 
17713  AdjustDeclIfTemplate(TagD);
17714  TagDecl *Tag = cast<TagDecl>(TagD);
17715  Tag->setInvalidDecl();
17716 
17717  // Make sure we "complete" the definition even it is invalid.
17718  if (Tag->isBeingDefined()) {
17719  if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17720  RD->completeDefinition();
17721  }
17722 
17723  // We're undoing ActOnTagStartDefinition here, not
17724  // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17725  // the FieldCollector.
17726 
17727  PopDeclContext();
17728 }
17729 
17730 // Note that FieldName may be null for anonymous bitfields.
17732  IdentifierInfo *FieldName, QualType FieldTy,
17733  bool IsMsStruct, Expr *BitWidth) {
17734  assert(BitWidth);
17735  if (BitWidth->containsErrors())
17736  return ExprError();
17737 
17738  // C99 6.7.2.1p4 - verify the field type.
17739  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
17740  if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
17741  // Handle incomplete and sizeless types with a specific error.
17742  if (RequireCompleteSizedType(FieldLoc, FieldTy,
17743  diag::err_field_incomplete_or_sizeless))
17744  return ExprError();
17745  if (FieldName)
17746  return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
17747  << FieldName << FieldTy << BitWidth->getSourceRange();
17748  return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
17749  << FieldTy << BitWidth->getSourceRange();
17750  } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
17751  UPPC_BitFieldWidth))
17752  return ExprError();
17753 
17754  // If the bit-width is type- or value-dependent, don't try to check
17755  // it now.
17756  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
17757  return BitWidth;
17758 
17760  ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
17761  if (ICE.isInvalid())
17762  return ICE;
17763  BitWidth = ICE.get();
17764 
17765  // Zero-width bitfield is ok for anonymous field.
17766  if (Value == 0 && FieldName)
17767  return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
17768 
17769  if (Value.isSigned() && Value.isNegative()) {
17770  if (FieldName)
17771  return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
17772  << FieldName << toString(Value, 10);
17773  return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
17774  << toString(Value, 10);
17775  }
17776 
17777  // The size of the bit-field must not exceed our maximum permitted object
17778  // size.
17779  if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
17780  return Diag(FieldLoc, diag::err_bitfield_too_wide)
17781  << !FieldName << FieldName << toString(Value, 10);
17782  }
17783 
17784  if (!FieldTy->isDependentType()) {
17785  uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
17786  uint64_t TypeWidth = Context.getIntWidth(FieldTy);
17787  bool BitfieldIsOverwide = Value.ugt(TypeWidth);
17788 
17789  // Over-wide bitfields are an error in C or when using the MSVC bitfield
17790  // ABI.
17791  bool CStdConstraintViolation =
17792  BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17793  bool MSBitfieldViolation =
17794  Value.ugt(TypeStorageSize) &&
17795  (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
17796  if (CStdConstraintViolation || MSBitfieldViolation) {
17797  unsigned DiagWidth =
17798  CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17799  return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17800  << (bool)FieldName << FieldName << toString(Value, 10)
17801  << !CStdConstraintViolation << DiagWidth;
17802  }
17803 
17804  // Warn on types where the user might conceivably expect to get all
17805  // specified bits as value bits: that's all integral types other than
17806  // 'bool'.
17807  if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
17808  Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17809  << FieldName << toString(Value, 10)
17810  << (unsigned)TypeWidth;
17811  }
17812  }
17813 
17814  return BitWidth;
17815 }
17816 
17817 /// ActOnField - Each field of a C struct/union is passed into this in order
17818 /// to create a FieldDecl object for it.
17820  Declarator &D, Expr *BitfieldWidth) {
17821  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
17822  DeclStart, D, static_cast<Expr*>(BitfieldWidth),
17823  /*InitStyle=*/ICIS_NoInit, AS_public);
17824  return Res;
17825 }
17826 
17827 /// HandleField - Analyze a field of a C struct or a C++ data member.
17828 ///
17830  SourceLocation DeclStart,
17831  Declarator &D, Expr *BitWidth,
17832  InClassInitStyle InitStyle,
17833  AccessSpecifier AS) {
17834  if (D.isDecompositionDeclarator()) {
17836  Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17837  << Decomp.getSourceRange();
17838  return nullptr;
17839  }
17840 
17841  IdentifierInfo *II = D.getIdentifier();
17842  SourceLocation Loc = DeclStart;
17843  if (II) Loc = D.getIdentifierLoc();
17844 
17845  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17846  QualType T = TInfo->getType();
17847  if (getLangOpts().CPlusPlus) {
17848  CheckExtraCXXDefaultArguments(D);
17849 
17850  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17851  UPPC_DataMemberType)) {
17852  D.setInvalidType();
17853  T = Context.IntTy;
17854  TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17855  }
17856  }
17857 
17858  DiagnoseFunctionSpecifiers(D.getDeclSpec());
17859 
17860  if (D.getDeclSpec().isInlineSpecified())
17861  Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17862  << getLangOpts().CPlusPlus17;
17865  diag::err_invalid_thread)
17866  << DeclSpec::getSpecifierName(TSCS);
17867 
17868  // Check to see if this name was declared as a member previously
17869  NamedDecl *PrevDecl = nullptr;
17870  LookupResult Previous(*this, II, Loc, LookupMemberName,
17871  ForVisibleRedeclaration);
17872  LookupName(Previous, S);
17873  switch (Previous.getResultKind()) {
17874  case LookupResult::Found:
17876  PrevDecl = Previous.getAsSingle<NamedDecl>();
17877  break;
17878 
17880  PrevDecl = Previous.getRepresentativeDecl();
17881  break;
17882 
17886  break;
17887  }
17888  Previous.suppressDiagnostics();
17889 
17890  if (PrevDecl && PrevDecl->isTemplateParameter()) {
17891  // Maybe we will complain about the shadowed template parameter.
17892  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17893  // Just pretend that we didn't see the previous declaration.
17894  PrevDecl = nullptr;
17895  }
17896 
17897  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17898  PrevDecl = nullptr;
17899 
17900  bool Mutable
17902  SourceLocation TSSL = D.getBeginLoc();
17903  FieldDecl *NewFD
17904  = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17905  TSSL, AS, PrevDecl, &D);
17906 
17907  if (NewFD->isInvalidDecl())
17908  Record->setInvalidDecl();
17909 
17911  NewFD->setModulePrivate();
17912 
17913  if (NewFD->isInvalidDecl() && PrevDecl) {
17914  // Don't introduce NewFD into scope; there's already something
17915  // with the same name in the same scope.
17916  } else if (II) {
17917  PushOnScopeChains(NewFD, S);
17918  } else
17919  Record->addDecl(NewFD);
17920 
17921  return NewFD;
17922 }
17923 
17924 /// Build a new FieldDecl and check its well-formedness.
17925 ///
17926 /// This routine builds a new FieldDecl given the fields name, type,
17927 /// record, etc. \p PrevDecl should refer to any previous declaration
17928 /// with the same name and in the same scope as the field to be
17929 /// created.
17930 ///
17931 /// \returns a new FieldDecl.
17932 ///
17933 /// \todo The Declarator argument is a hack. It will be removed once
17935  TypeSourceInfo *TInfo,
17936  RecordDecl *Record, SourceLocation Loc,
17937  bool Mutable, Expr *BitWidth,
17938  InClassInitStyle InitStyle,
17939  SourceLocation TSSL,
17940  AccessSpecifier AS, NamedDecl *PrevDecl,
17941  Declarator *D) {
17942  IdentifierInfo *II = Name.getAsIdentifierInfo();
17943  bool InvalidDecl = false;
17944  if (D) InvalidDecl = D->isInvalidType();
17945 
17946  // If we receive a broken type, recover by assuming 'int' and
17947  // marking this declaration as invalid.
17948  if (T.isNull() || T->containsErrors()) {
17949  InvalidDecl = true;
17950  T = Context.IntTy;
17951  }
17952 
17953  QualType EltTy = Context.getBaseElementType(T);
17954  if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17955  if (RequireCompleteSizedType(Loc, EltTy,
17956  diag::err_field_incomplete_or_sizeless)) {
17957  // Fields of incomplete type force their record to be invalid.
17958  Record->setInvalidDecl();
17959  InvalidDecl = true;
17960  } else {
17961  NamedDecl *Def;
17962  EltTy->isIncompleteType(&Def);
17963  if (Def && Def->isInvalidDecl()) {
17964  Record->setInvalidDecl();
17965  InvalidDecl = true;
17966  }
17967  }
17968  }
17969 
17970  // TR 18037 does not allow fields to be declared with address space
17971  if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17973  Diag(Loc, diag::err_field_with_address_space);
17974  Record->setInvalidDecl();
17975  InvalidDecl = true;
17976  }
17977 
17978  if (LangOpts.OpenCL) {
17979  // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17980  // used as structure or union field: image, sampler, event or block types.
17981  if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17982  T->isBlockPointerType()) {
17983  Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17984  Record->setInvalidDecl();
17985  InvalidDecl = true;
17986  }
17987  // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17988  // is enabled.
17989  if (BitWidth && !getOpenCLOptions().isAvailableOption(
17990  "__cl_clang_bitfields", LangOpts)) {
17991  Diag(Loc, diag::err_opencl_bitfields);
17992  InvalidDecl = true;
17993  }
17994  }
17995 
17996  // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17997  if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17998  T.hasQualifiers()) {
17999  InvalidDecl = true;
18000  Diag(Loc, diag::err_anon_bitfield_qualifiers);
18001  }
18002 
18003  // C99 6.7.2.1p8: A member of a structure or union may have any type other
18004  // than a variably modified type.
18005  if (!InvalidDecl && T->isVariablyModifiedType()) {
18006  if (!tryToFixVariablyModifiedVarType(
18007  TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18008  InvalidDecl = true;
18009  }
18010 
18011  // Fields can not have abstract class types
18012  if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18013  diag::err_abstract_type_in_decl,
18014  AbstractFieldType))
18015  InvalidDecl = true;
18016 
18017  if (InvalidDecl)
18018  BitWidth = nullptr;
18019  // If this is declared as a bit-field, check the bit-field.
18020  if (BitWidth) {
18021  BitWidth =
18022  VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18023  if (!BitWidth) {
18024  InvalidDecl = true;
18025  BitWidth = nullptr;
18026  }
18027  }
18028 
18029  // Check that 'mutable' is consistent with the type of the declaration.
18030  if (!InvalidDecl && Mutable) {
18031  unsigned DiagID = 0;
18032  if (T->isReferenceType())
18033  DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18034  : diag::err_mutable_reference;
18035  else if (T.isConstQualified())
18036  DiagID = diag::err_mutable_const;
18037 
18038  if (DiagID) {
18039  SourceLocation ErrLoc = Loc;
18040  if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18041  ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18042  Diag(ErrLoc, DiagID);
18043  if (DiagID != diag::ext_mutable_reference) {
18044  Mutable = false;
18045  InvalidDecl = true;
18046  }
18047  }
18048  }
18049 
18050  // C++11 [class.union]p8 (DR1460):
18051  // At most one variant member of a union may have a
18052  // brace-or-equal-initializer.
18053  if (InitStyle != ICIS_NoInit)
18054  checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18055 
18056  FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18057  BitWidth, Mutable, InitStyle);
18058  if (InvalidDecl)
18059  NewFD->setInvalidDecl();
18060 
18061  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
18062  Diag(Loc, diag::err_duplicate_member) << II;
18063  Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18064  NewFD->setInvalidDecl();
18065  }
18066 
18067  if (!InvalidDecl && getLangOpts().CPlusPlus) {
18068  if (Record->isUnion()) {
18069  if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18070  CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18071  if (RDecl->getDefinition()) {
18072  // C++ [class.union]p1: An object of a class with a non-trivial
18073  // constructor, a non-trivial copy constructor, a non-trivial
18074  // destructor, or a non-trivial copy assignment operator
18075  // cannot be a member of a union, nor can an array of such
18076  // objects.
18077  if (CheckNontrivialField(NewFD))
18078  NewFD->setInvalidDecl();
18079  }
18080  }
18081 
18082  // C++ [class.union]p1: If a union contains a member of reference type,
18083  // the program is ill-formed, except when compiling with MSVC extensions
18084  // enabled.
18085  if (EltTy->isReferenceType()) {
18086  Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
18087  diag::ext_union_member_of_reference_type :
18088  diag::err_union_member_of_reference_type)
18089  << NewFD->getDeclName() << EltTy;
18090  if (!getLangOpts().MicrosoftExt)
18091  NewFD->setInvalidDecl();
18092  }
18093  }
18094  }
18095 
18096  // FIXME: We need to pass in the attributes given an AST
18097  // representation, not a parser representation.
18098  if (D) {
18099  // FIXME: The current scope is almost... but not entirely... correct here.
18100  ProcessDeclAttributes(getCurScope(), NewFD, *D);
18101 
18102  if (NewFD->hasAttrs())
18103  CheckAlignasUnderalignment(NewFD);
18104  }
18105 
18106  // In auto-retain/release, infer strong retension for fields of
18107  // retainable type.
18108  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
18109  NewFD->setInvalidDecl();
18110 
18111  if (T.isObjCGCWeak())
18112  Diag(Loc, diag::warn_attribute_weak_on_field);
18113 
18114  // PPC MMA non-pointer types are not allowed as field types.
18115  if (Context.getTargetInfo().getTriple().isPPC64() &&
18116  CheckPPCMMAType(T, NewFD->getLocation()))
18117  NewFD->setInvalidDecl();
18118 
18119  NewFD->setAccess(AS);
18120  return NewFD;
18121 }
18122 
18124  assert(FD);
18125  assert(getLangOpts().CPlusPlus && "valid check only for C++");
18126 
18127  if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18128  return false;
18129 
18130  QualType EltTy = Context.getBaseElementType(FD->getType());
18131  if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18132  CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18133  if (RDecl->getDefinition()) {
18134  // We check for copy constructors before constructors
18135  // because otherwise we'll never get complaints about
18136  // copy constructors.
18137 
18138  CXXSpecialMember member = CXXInvalid;
18139  // We're required to check for any non-trivial constructors. Since the
18140  // implicit default constructor is suppressed if there are any
18141  // user-declared constructors, we just need to check that there is a
18142  // trivial default constructor and a trivial copy constructor. (We don't
18143  // worry about move constructors here, since this is a C++98 check.)
18144  if (RDecl->hasNonTrivialCopyConstructor())
18145  member = CXXCopyConstructor;
18146  else if (!RDecl->hasTrivialDefaultConstructor())
18147  member = CXXDefaultConstructor;
18148  else if (RDecl->hasNonTrivialCopyAssignment())
18149  member = CXXCopyAssignment;
18150  else if (RDecl->hasNonTrivialDestructor())
18151  member = CXXDestructor;
18152 
18153  if (member != CXXInvalid) {
18154  if (!getLangOpts().CPlusPlus11 &&
18155  getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18156  // Objective-C++ ARC: it is an error to have a non-trivial field of
18157  // a union. However, system headers in Objective-C programs
18158  // occasionally have Objective-C lifetime objects within unions,
18159  // and rather than cause the program to fail, we make those
18160  // members unavailable.
18161  SourceLocation Loc = FD->getLocation();
18162  if (getSourceManager().isInSystemHeader(Loc)) {
18163  if (!FD->hasAttr<UnavailableAttr>())
18164  FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18165  UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18166  return false;
18167  }
18168  }
18169 
18170  Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
18171  diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
18172  diag::err_illegal_union_or_anon_struct_member)
18173  << FD->getParent()->isUnion() << FD->getDeclName() << member;
18174  DiagnoseNontrivial(RDecl, member);
18175  return !getLangOpts().CPlusPlus11;
18176  }
18177  }
18178  }
18179 
18180  return false;
18181 }
18182 
18183 /// TranslateIvarVisibility - Translate visibility from a token ID to an
18184 /// AST enum value.
18187  switch (ivarVisibility) {
18188  default: llvm_unreachable("Unknown visitibility kind");
18189  case tok::objc_private: return ObjCIvarDecl::Private;
18190  case tok::objc_public: return ObjCIvarDecl::Public;
18191  case tok::objc_protected: return ObjCIvarDecl::Protected;
18192  case tok::objc_package: return ObjCIvarDecl::Package;
18193  }
18194 }
18195 
18196 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
18197 /// in order to create an IvarDecl object for it.
18199  SourceLocation DeclStart,
18200  Declarator &D, Expr *BitfieldWidth,
18202 
18203  IdentifierInfo *II = D.getIdentifier();
18204  Expr *BitWidth = (Expr*)BitfieldWidth;
18205  SourceLocation Loc = DeclStart;
18206  if (II) Loc = D.getIdentifierLoc();
18207 
18208  // FIXME: Unnamed fields can be handled in various different ways, for
18209  // example, unnamed unions inject all members into the struct namespace!
18210 
18211  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18212  QualType T = TInfo->getType();
18213 
18214  if (BitWidth) {
18215  // 6.7.2.1p3, 6.7.2.1p4
18216  BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
18217  if (!BitWidth)
18218  D.setInvalidType();
18219  } else {
18220  // Not a bitfield.
18221 
18222  // validate II.
18223 
18224  }
18225  if (T->isReferenceType()) {
18226  Diag(Loc, diag::err_ivar_reference_type);
18227  D.setInvalidType();
18228  }
18229  // C99 6.7.2.1p8: A member of a structure or union may have any type other
18230  // than a variably modified type.
18231  else if (T->isVariablyModifiedType()) {
18232  if (!tryToFixVariablyModifiedVarType(
18233  TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
18234  D.setInvalidType();
18235  }
18236 
18237  // Get the visibility (access control) for this ivar.
18239  Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
18241  // Must set ivar's DeclContext to its enclosing interface.
18242  ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
18243  if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
18244  return nullptr;
18245  ObjCContainerDecl *EnclosingContext;
18246  if (ObjCImplementationDecl *IMPDecl =
18247  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18248  if (LangOpts.ObjCRuntime.isFragile()) {
18249  // Case of ivar declared in an implementation. Context is that of its class.
18250  EnclosingContext = IMPDecl->getClassInterface();
18251  assert(EnclosingContext && "Implementation has no class interface!");
18252  }
18253  else
18254  EnclosingContext = EnclosingDecl;
18255  } else {
18256  if (ObjCCategoryDecl *CDecl =
18257  dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18258  if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
18259  Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
18260  return nullptr;
18261  }
18262  }
18263  EnclosingContext = EnclosingDecl;
18264  }
18265 
18266  // Construct the decl.
18267  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
18268  DeclStart, Loc, II, T,
18269  TInfo, ac, (Expr *)BitfieldWidth);
18270 
18271  if (II) {
18272  NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
18273  ForVisibleRedeclaration);
18274  if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
18275  && !isa<TagDecl>(PrevDecl)) {
18276  Diag(Loc, diag::err_duplicate_member) << II;
18277  Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18278  NewID->setInvalidDecl();
18279  }
18280  }
18281 
18282  // Process attributes attached to the ivar.
18283  ProcessDeclAttributes(S, NewID, D);
18284 
18285  if (D.isInvalidType())
18286  NewID->setInvalidDecl();
18287 
18288  // In ARC, infer 'retaining' for ivars of retainable type.
18289  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
18290  NewID->setInvalidDecl();
18291 
18293  NewID->setModulePrivate();
18294 
18295  if (II) {
18296  // FIXME: When interfaces are DeclContexts, we'll need to add
18297  // these to the interface.
18298  S->AddDecl(NewID);
18299  IdResolver.AddDecl(NewID);
18300  }
18301 
18302  if (LangOpts.ObjCRuntime.isNonFragile() &&
18303  !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
18304  Diag(Loc, diag::warn_ivars_in_interface);
18305 
18306  return NewID;
18307 }
18308 
18309 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
18310 /// class and class extensions. For every class \@interface and class
18311 /// extension \@interface, if the last ivar is a bitfield of any type,
18312 /// then add an implicit `char :0` ivar to the end of that interface.
18314  SmallVectorImpl<Decl *> &AllIvarDecls) {
18315  if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
18316  return;
18317 
18318  Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18319  ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
18320 
18321  if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
18322  return;
18323  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
18324  if (!ID) {
18325  if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
18326  if (!CD->IsClassExtension())
18327  return;
18328  }
18329  // No need to add this to end of @implementation.
18330  else
18331  return;
18332  }
18333  // All conditions are met. Add a new bitfield to the tail end of ivars.
18334  llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18335  Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18336 
18337  Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
18338  DeclLoc, DeclLoc, nullptr,
18339  Context.CharTy,
18340  Context.getTrivialTypeSourceInfo(Context.CharTy,
18341  DeclLoc),
18343  true);
18344  AllIvarDecls.push_back(Ivar);
18345 }
18346 
18347 /// [class.dtor]p4:
18348 /// At the end of the definition of a class, overload resolution is
18349 /// performed among the prospective destructors declared in that class with
18350 /// an empty argument list to select the destructor for the class, also
18351 /// known as the selected destructor.
18352 ///
18353 /// We do the overload resolution here, then mark the selected constructor in the AST.
18354 /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18356  if (!Record->hasUserDeclaredDestructor()) {
18357  return;
18358  }
18359 
18360  SourceLocation Loc = Record->getLocation();
18362 
18363  for (auto *Decl : Record->decls()) {
18364  if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18365  if (DD->isInvalidDecl())
18366  continue;
18367  S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18368  OCS);
18369  assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18370  }
18371  }
18372 
18373  if (OCS.empty()) {
18374  return;
18375  }
18377  unsigned Msg = 0;
18378  OverloadCandidateDisplayKind DisplayKind;
18379 
18380  switch (OCS.BestViableFunction(S, Loc, Best)) {
18381  case OR_Success:
18382  case OR_Deleted:
18383  Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18384  break;
18385 
18386  case OR_Ambiguous:
18387  Msg = diag::err_ambiguous_destructor;
18388  DisplayKind = OCD_AmbiguousCandidates;
18389  break;
18390 
18391  case OR_No_Viable_Function:
18392  Msg = diag::err_no_viable_destructor;
18393  DisplayKind = OCD_AllCandidates;
18394  break;
18395  }
18396 
18397  if (Msg) {
18398  // OpenCL have got their own thing going with destructors. It's slightly broken,
18399  // but we allow it.
18400  if (!S.LangOpts.OpenCL) {
18401  PartialDiagnostic Diag = S.PDiag(Msg) << Record;
18402  OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
18403  Record->setInvalidDecl();
18404  }
18405  // It's a bit hacky: At this point we've raised an error but we want the
18406  // rest of the compiler to continue somehow working. However almost
18407  // everything we'll try to do with the class will depend on there being a
18408  // destructor. So let's pretend the first one is selected and hope for the
18409  // best.
18410  Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18411  }
18412 }
18413 
18414 /// [class.mem.special]p5
18415 /// Two special member functions are of the same kind if:
18416 /// - they are both default constructors,
18417 /// - they are both copy or move constructors with the same first parameter
18418 /// type, or
18419 /// - they are both copy or move assignment operators with the same first
18420 /// parameter type and the same cv-qualifiers and ref-qualifier, if any.
18422  CXXMethodDecl *M1,
18423  CXXMethodDecl *M2,
18424  Sema::CXXSpecialMember CSM) {
18425  // We don't want to compare templates to non-templates: See
18426  // https://github.com/llvm/llvm-project/issues/59206
18427  if (CSM == Sema::CXXDefaultConstructor)
18428  return bool(M1->getDescribedFunctionTemplate()) ==
18430  if (!Context.hasSameType(M1->getParamDecl(0)->getType(),
18431  M2->getParamDecl(0)->getType()))
18432  return false;
18433  if (!Context.hasSameType(M1->getThisType(), M2->getThisType()))
18434  return false;
18435 
18436  return true;
18437 }
18438 
18439 /// [class.mem.special]p6:
18440 /// An eligible special member function is a special member function for which:
18441 /// - the function is not deleted,
18442 /// - the associated constraints, if any, are satisfied, and
18443 /// - no special member function of the same kind whose associated constraints
18444 /// [CWG2595], if any, are satisfied is more constrained.
18445 static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
18446  ArrayRef<CXXMethodDecl *> Methods,
18447  Sema::CXXSpecialMember CSM) {
18448  SmallVector<bool, 4> SatisfactionStatus;
18449 
18450  for (CXXMethodDecl *Method : Methods) {
18451  const Expr *Constraints = Method->getTrailingRequiresClause();
18452  if (!Constraints)
18453  SatisfactionStatus.push_back(true);
18454  else {
18455  ConstraintSatisfaction Satisfaction;
18456  if (S.CheckFunctionConstraints(Method, Satisfaction))
18457  SatisfactionStatus.push_back(false);
18458  else
18459  SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
18460  }
18461  }
18462 
18463  for (size_t i = 0; i < Methods.size(); i++) {
18464  if (!SatisfactionStatus[i])
18465  continue;
18466  CXXMethodDecl *Method = Methods[i];
18467  CXXMethodDecl *OrigMethod = Method;
18468  if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18469  OrigMethod = cast<CXXMethodDecl>(MF);
18470 
18471  const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18472  bool AnotherMethodIsMoreConstrained = false;
18473  for (size_t j = 0; j < Methods.size(); j++) {
18474  if (i == j || !SatisfactionStatus[j])
18475  continue;
18476  CXXMethodDecl *OtherMethod = Methods[j];
18477  if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
18478  OtherMethod = cast<CXXMethodDecl>(MF);
18479 
18480  if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
18481  CSM))
18482  continue;
18483 
18484  const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
18485  if (!OtherConstraints)
18486  continue;
18487  if (!Constraints) {
18488  AnotherMethodIsMoreConstrained = true;
18489  break;
18490  }
18491  if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
18492  {Constraints},
18493  AnotherMethodIsMoreConstrained)) {
18494  // There was an error with the constraints comparison. Exit the loop
18495  // and don't consider this function eligible.
18496  AnotherMethodIsMoreConstrained = true;
18497  }
18498  if (AnotherMethodIsMoreConstrained)
18499  break;
18500  }
18501  // FIXME: Do not consider deleted methods as eligible after implementing
18502  // DR1734 and DR1496.
18503  if (!AnotherMethodIsMoreConstrained) {
18504  Method->setIneligibleOrNotSelected(false);
18505  Record->addedEligibleSpecialMemberFunction(Method, 1 << CSM);
18506  }
18507  }
18508 }
18509 
18511  CXXRecordDecl *Record) {
18512  SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
18513  SmallVector<CXXMethodDecl *, 4> CopyConstructors;
18514  SmallVector<CXXMethodDecl *, 4> MoveConstructors;
18515  SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
18516  SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
18517 
18518  for (auto *Decl : Record->decls()) {
18519  auto *MD = dyn_cast<CXXMethodDecl>(Decl);
18520  if (!MD) {
18521  auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
18522  if (FTD)
18523  MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
18524  }
18525  if (!MD)
18526  continue;
18527  if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
18528  if (CD->isInvalidDecl())
18529  continue;
18530  if (CD->isDefaultConstructor())
18531  DefaultConstructors.push_back(MD);
18532  else if (CD->isCopyConstructor())
18533  CopyConstructors.push_back(MD);
18534  else if (CD->isMoveConstructor())
18535  MoveConstructors.push_back(MD);
18536  } else if (MD->isCopyAssignmentOperator()) {
18537  CopyAssignmentOperators.push_back(MD);
18538  } else if (MD->isMoveAssignmentOperator()) {
18539  MoveAssignmentOperators.push_back(MD);
18540  }
18541  }
18542 
18543  SetEligibleMethods(S, Record, DefaultConstructors,
18545  SetEligibleMethods(S, Record, CopyConstructors, Sema::CXXCopyConstructor);
18546  SetEligibleMethods(S, Record, MoveConstructors, Sema::CXXMoveConstructor);
18547  SetEligibleMethods(S, Record, CopyAssignmentOperators,
18549  SetEligibleMethods(S, Record, MoveAssignmentOperators,
18551 }
18552 
18553 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
18554  ArrayRef<Decl *> Fields, SourceLocation LBrac,
18555  SourceLocation RBrac,
18556  const ParsedAttributesView &Attrs) {
18557  assert(EnclosingDecl && "missing record or interface decl");
18558 
18559  // If this is an Objective-C @implementation or category and we have
18560  // new fields here we should reset the layout of the interface since
18561  // it will now change.
18562  if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
18563  ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
18564  switch (DC->getKind()) {
18565  default: break;
18566  case Decl::ObjCCategory:
18567  Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
18568  break;
18569  case Decl::ObjCImplementation:
18570  Context.
18571  ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
18572  break;
18573  }
18574  }
18575 
18576  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
18577  CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
18578 
18579  // Start counting up the number of named members; make sure to include
18580  // members of anonymous structs and unions in the total.
18581  unsigned NumNamedMembers = 0;
18582  if (Record) {
18583  for (const auto *I : Record->decls()) {
18584  if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
18585  if (IFD->getDeclName())
18586  ++NumNamedMembers;
18587  }
18588  }
18589 
18590  // Verify that all the fields are okay.
18591  SmallVector<FieldDecl*, 32> RecFields;
18592 
18593  for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
18594  i != end; ++i) {
18595  FieldDecl *FD = cast<FieldDecl>(*i);
18596 
18597  // Get the type for the field.
18598  const Type *FDTy = FD->getType().getTypePtr();
18599 
18600  if (!FD->isAnonymousStructOrUnion()) {
18601  // Remember all fields written by the user.
18602  RecFields.push_back(FD);
18603  }
18604 
18605  // If the field is already invalid for some reason, don't emit more
18606  // diagnostics about it.
18607  if (FD->isInvalidDecl()) {
18608  EnclosingDecl->setInvalidDecl();
18609  continue;
18610  }
18611 
18612  // C99 6.7.2.1p2:
18613  // A structure or union shall not contain a member with
18614  // incomplete or function type (hence, a structure shall not
18615  // contain an instance of itself, but may contain a pointer to
18616  // an instance of itself), except that the last member of a
18617  // structure with more than one named member may have incomplete
18618  // array type; such a structure (and any union containing,
18619  // possibly recursively, a member that is such a structure)
18620  // shall not be a member of a structure or an element of an
18621  // array.
18622  bool IsLastField = (i + 1 == Fields.end());
18623  if (FDTy->isFunctionType()) {
18624  // Field declared as a function.
18625  Diag(FD->getLocation(), diag::err_field_declared_as_function)
18626  << FD->getDeclName();
18627  FD->setInvalidDecl();
18628  EnclosingDecl->setInvalidDecl();
18629  continue;
18630  } else if (FDTy->isIncompleteArrayType() &&
18631  (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
18632  if (Record) {
18633  // Flexible array member.
18634  // Microsoft and g++ is more permissive regarding flexible array.
18635  // It will accept flexible array in union and also
18636  // as the sole element of a struct/class.
18637  unsigned DiagID = 0;
18638  if (!Record->isUnion() && !IsLastField) {
18639  Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
18640  << FD->getDeclName() << FD->getType() << Record->getTagKind();
18641  Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
18642  FD->setInvalidDecl();
18643  EnclosingDecl->setInvalidDecl();
18644  continue;
18645  } else if (Record->isUnion())
18646  DiagID = getLangOpts().MicrosoftExt
18647  ? diag::ext_flexible_array_union_ms
18648  : getLangOpts().CPlusPlus
18649  ? diag::ext_flexible_array_union_gnu
18650  : diag::err_flexible_array_union;
18651  else if (NumNamedMembers < 1)
18652  DiagID = getLangOpts().MicrosoftExt
18653  ? diag::ext_flexible_array_empty_aggregate_ms
18654  : getLangOpts().CPlusPlus
18655  ? diag::ext_flexible_array_empty_aggregate_gnu
18656  : diag::err_flexible_array_empty_aggregate;
18657 
18658  if (DiagID)
18659  Diag(FD->getLocation(), DiagID) << FD->getDeclName()
18660  << Record->getTagKind();
18661  // While the layout of types that contain virtual bases is not specified
18662  // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
18663  // virtual bases after the derived members. This would make a flexible
18664  // array member declared at the end of an object not adjacent to the end
18665  // of the type.
18666  if (CXXRecord && CXXRecord->getNumVBases() != 0)
18667  Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
18668  << FD->getDeclName() << Record->getTagKind();
18669  if (!getLangOpts().C99)
18670  Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
18671  << FD->getDeclName() << Record->getTagKind();
18672 
18673  // If the element type has a non-trivial destructor, we would not
18674  // implicitly destroy the elements, so disallow it for now.
18675  //
18676  // FIXME: GCC allows this. We should probably either implicitly delete
18677  // the destructor of the containing class, or just allow this.
18678  QualType BaseElem = Context.getBaseElementType(FD->getType());
18679  if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
18680  Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
18681  << FD->getDeclName() << FD->getType();
18682  FD->setInvalidDecl();
18683  EnclosingDecl->setInvalidDecl();
18684  continue;
18685  }
18686  // Okay, we have a legal flexible array member at the end of the struct.
18687  Record->setHasFlexibleArrayMember(true);
18688  } else {
18689  // In ObjCContainerDecl ivars with incomplete array type are accepted,
18690  // unless they are followed by another ivar. That check is done
18691  // elsewhere, after synthesized ivars are known.
18692  }
18693  } else if (!FDTy->isDependentType() &&
18694  RequireCompleteSizedType(
18695  FD->getLocation(), FD->getType(),
18696  diag::err_field_incomplete_or_sizeless)) {
18697  // Incomplete type
18698  FD->setInvalidDecl();
18699  EnclosingDecl->setInvalidDecl();
18700  continue;
18701  } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
18702  if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
18703  // A type which contains a flexible array member is considered to be a
18704  // flexible array member.
18705  Record->setHasFlexibleArrayMember(true);
18706  if (!Record->isUnion()) {
18707  // If this is a struct/class and this is not the last element, reject
18708  // it. Note that GCC supports variable sized arrays in the middle of
18709  // structures.
18710  if (!IsLastField)
18711  Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
18712  << FD->getDeclName() << FD->getType();
18713  else {
18714  // We support flexible arrays at the end of structs in
18715  // other structs as an extension.
18716  Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
18717  << FD->getDeclName();
18718  }
18719  }
18720  }
18721  if (isa<ObjCContainerDecl>(EnclosingDecl) &&
18722  RequireNonAbstractType(FD->getLocation(), FD->getType(),
18723  diag::err_abstract_type_in_decl,
18724  AbstractIvarType)) {
18725  // Ivars can not have abstract class types
18726  FD->setInvalidDecl();
18727  }
18728  if (Record && FDTTy->getDecl()->hasObjectMember())
18729  Record->setHasObjectMember(true);
18730  if (Record && FDTTy->getDecl()->hasVolatileMember())
18731  Record->setHasVolatileMember(true);
18732  } else if (FDTy->isObjCObjectType()) {
18733  /// A field cannot be an Objective-c object
18734  Diag(FD->getLocation(), diag::err_statically_allocated_object)
18735  << FixItHint::CreateInsertion(FD->getLocation(), "*");
18736  QualType T = Context.getObjCObjectPointerType(FD->getType());
18737  FD->setType(T);
18738  } else if (Record && Record->isUnion() &&
18740  getSourceManager().isInSystemHeader(FD->getLocation()) &&
18741  !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
18743  !Context.hasDirectOwnershipQualifier(FD->getType()))) {
18744  // For backward compatibility, fields of C unions declared in system
18745  // headers that have non-trivial ObjC ownership qualifications are marked
18746  // as unavailable unless the qualifier is explicit and __strong. This can
18747  // break ABI compatibility between programs compiled with ARC and MRR, but
18748  // is a better option than rejecting programs using those unions under
18749  // ARC.
18750  FD->addAttr(UnavailableAttr::CreateImplicit(
18751  Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
18752  FD->getLocation()));
18753  } else if (getLangOpts().ObjC &&
18754  getLangOpts().getGC() != LangOptions::NonGC && Record &&
18755  !Record->hasObjectMember()) {
18756  if (FD->getType()->isObjCObjectPointerType() ||
18757  FD->getType().isObjCGCStrong())
18758  Record->setHasObjectMember(true);
18759  else if (Context.getAsArrayType(FD->getType())) {
18760  QualType BaseType = Context.getBaseElementType(FD->getType());
18761  if (BaseType->isRecordType() &&
18762  BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
18763  Record->setHasObjectMember(true);
18764  else if (BaseType->isObjCObjectPointerType() ||
18765  BaseType.isObjCGCStrong())
18766  Record->setHasObjectMember(true);
18767  }
18768  }
18769 
18770  if (Record && !getLangOpts().CPlusPlus &&
18771  !shouldIgnoreForRecordTriviality(FD)) {
18772  QualType FT = FD->getType();
18776  Record->isUnion())
18778  }
18781  Record->setNonTrivialToPrimitiveCopy(true);
18782  if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
18784  }
18785  if (FT.isDestructedType()) {
18786  Record->setNonTrivialToPrimitiveDestroy(true);
18787  Record->setParamDestroyedInCallee(true);
18788  if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
18790  }
18791 
18792  if (const auto *RT = FT->getAs<RecordType>()) {
18793  if (RT->getDecl()->getArgPassingRestrictions() ==
18796  } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
18798  }
18799 
18800  if (Record && FD->getType().isVolatileQualified())
18801  Record->setHasVolatileMember(true);
18802  // Keep track of the number of named members.
18803  if (FD->getIdentifier())
18804  ++NumNamedMembers;
18805  }
18806 
18807  // Okay, we successfully defined 'Record'.
18808  if (Record) {
18809  bool Completed = false;
18810  if (CXXRecord) {
18811  if (!CXXRecord->isInvalidDecl()) {
18812  // Set access bits correctly on the directly-declared conversions.
18814  I = CXXRecord->conversion_begin(),
18815  E = CXXRecord->conversion_end(); I != E; ++I)
18816  I.setAccess((*I)->getAccess());
18817  }
18818 
18819  // Add any implicitly-declared members to this class.
18820  AddImplicitlyDeclaredMembersToClass(CXXRecord);
18821 
18822  if (!CXXRecord->isDependentType()) {
18823  if (!CXXRecord->isInvalidDecl()) {
18824  // If we have virtual base classes, we may end up finding multiple
18825  // final overriders for a given virtual function. Check for this
18826  // problem now.
18827  if (CXXRecord->getNumVBases()) {
18828  CXXFinalOverriderMap FinalOverriders;
18829  CXXRecord->getFinalOverriders(FinalOverriders);
18830 
18831  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
18832  MEnd = FinalOverriders.end();
18833  M != MEnd; ++M) {
18834  for (OverridingMethods::iterator SO = M->second.begin(),
18835  SOEnd = M->second.end();
18836  SO != SOEnd; ++SO) {
18837  assert(SO->second.size() > 0 &&
18838  "Virtual function without overriding functions?");
18839  if (SO->second.size() == 1)
18840  continue;
18841 
18842  // C++ [class.virtual]p2:
18843  // In a derived class, if a virtual member function of a base
18844  // class subobject has more than one final overrider the
18845  // program is ill-formed.
18846  Diag(Record->getLocation(), diag::err_multiple_final_overriders)
18847  << (const NamedDecl *)M->first << Record;
18848  Diag(M->first->getLocation(),
18849  diag::note_overridden_virtual_function);
18851  OM = SO->second.begin(),
18852  OMEnd = SO->second.end();
18853  OM != OMEnd; ++OM)
18854  Diag(OM->Method->getLocation(), diag::note_final_overrider)
18855  << (const NamedDecl *)M->first << OM->Method->getParent();
18856 
18857  Record->setInvalidDecl();
18858  }
18859  }
18860  CXXRecord->completeDefinition(&FinalOverriders);
18861  Completed = true;
18862  }
18863  }
18864  ComputeSelectedDestructor(*this, CXXRecord);
18865  ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord);
18866  }
18867  }
18868 
18869  if (!Completed)
18870  Record->completeDefinition();
18871 
18872  // Handle attributes before checking the layout.
18873  ProcessDeclAttributeList(S, Record, Attrs);
18874 
18875  // Check to see if a FieldDecl is a pointer to a function.
18876  auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
18877  const FieldDecl *FD = dyn_cast<FieldDecl>(D);
18878  if (!FD) {
18879  // Check whether this is a forward declaration that was inserted by
18880  // Clang. This happens when a non-forward declared / defined type is
18881  // used, e.g.:
18882  //
18883  // struct foo {
18884  // struct bar *(*f)();
18885  // struct bar *(*g)();
18886  // };
18887  //
18888  // "struct bar" shows up in the decl AST as a "RecordDecl" with an
18889  // incomplete definition.
18890  if (const auto *TD = dyn_cast<TagDecl>(D))
18891  return !TD->isCompleteDefinition();
18892  return false;
18893  }
18894  QualType FieldType = FD->getType().getDesugaredType(Context);
18895  if (isa<PointerType>(FieldType)) {
18896  QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
18897  return PointeeType.getDesugaredType(Context)->isFunctionType();
18898  }
18899  return false;
18900  };
18901 
18902  // Maybe randomize the record's decls. We automatically randomize a record
18903  // of function pointers, unless it has the "no_randomize_layout" attribute.
18904  if (!getLangOpts().CPlusPlus &&
18905  (Record->hasAttr<RandomizeLayoutAttr>() ||
18906  (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
18907  llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
18908  !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
18909  !Record->isRandomized()) {
18910  SmallVector<Decl *, 32> NewDeclOrdering;
18911  if (randstruct::randomizeStructureLayout(Context, Record,
18912  NewDeclOrdering))
18913  Record->reorderDecls(NewDeclOrdering);
18914  }
18915 
18916  // We may have deferred checking for a deleted destructor. Check now.
18917  if (CXXRecord) {
18918  auto *Dtor = CXXRecord->getDestructor();
18919  if (Dtor && Dtor->isImplicit() &&
18920  ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
18921  CXXRecord->setImplicitDestructorIsDeleted();
18922  SetDeclDeleted(Dtor, CXXRecord->getLocation());
18923  }
18924  }
18925 
18926  if (Record->hasAttrs()) {
18927  CheckAlignasUnderalignment(Record);
18928 
18929  if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
18930  checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
18931  IA->getRange(), IA->getBestCase(),
18932  IA->getInheritanceModel());
18933  }
18934 
18935  // Check if the structure/union declaration is a type that can have zero
18936  // size in C. For C this is a language extension, for C++ it may cause
18937  // compatibility problems.
18938  bool CheckForZeroSize;
18939  if (!getLangOpts().CPlusPlus) {
18940  CheckForZeroSize = true;
18941  } else {
18942  // For C++ filter out types that cannot be referenced in C code.
18943  CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
18944  CheckForZeroSize =
18945  CXXRecord->getLexicalDeclContext()->isExternCContext() &&
18946  !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
18947  CXXRecord->isCLike();
18948  }
18949  if (CheckForZeroSize) {
18950  bool ZeroSize = true;
18951  bool IsEmpty = true;
18952  unsigned NonBitFields = 0;
18953  for (RecordDecl::field_iterator I = Record->field_begin(),
18954  E = Record->field_end();
18955  (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
18956  IsEmpty = false;
18957  if (I->isUnnamedBitfield()) {
18958  if (!I->isZeroLengthBitField(Context))
18959  ZeroSize = false;
18960  } else {
18961  ++NonBitFields;
18962  QualType FieldType = I->getType();
18963  if (FieldType->isIncompleteType() ||
18964  !Context.getTypeSizeInChars(FieldType).isZero())
18965  ZeroSize = false;
18966  }
18967  }
18968 
18969  // Empty structs are an extension in C (C99 6.7.2.1p7). They are
18970  // allowed in C++, but warn if its declaration is inside
18971  // extern "C" block.
18972  if (ZeroSize) {
18973  Diag(RecLoc, getLangOpts().CPlusPlus ?
18974  diag::warn_zero_size_struct_union_in_extern_c :
18975  diag::warn_zero_size_struct_union_compat)
18976  << IsEmpty << Record->isUnion() << (NonBitFields > 1);
18977  }
18978 
18979  // Structs without named members are extension in C (C99 6.7.2.1p7),
18980  // but are accepted by GCC.
18981  if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
18982  Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
18983  diag::ext_no_named_members_in_struct_union)
18984  << Record->isUnion();
18985  }
18986  }
18987  } else {
18988  ObjCIvarDecl **ClsFields =
18989  reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
18990  if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
18991  ID->setEndOfDefinitionLoc(RBrac);
18992  // Add ivar's to class's DeclContext.
18993  for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18994  ClsFields[i]->setLexicalDeclContext(ID);
18995  ID->addDecl(ClsFields[i]);
18996  }
18997  // Must enforce the rule that ivars in the base classes may not be
18998  // duplicates.
18999  if (ID->getSuperClass())
19000  DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19001  } else if (ObjCImplementationDecl *IMPDecl =
19002  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19003  assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19004  for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19005  // Ivar declared in @implementation never belongs to the implementation.
19006  // Only it is in implementation's lexical context.
19007  ClsFields[I]->setLexicalDeclContext(IMPDecl);
19008  CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
19009  IMPDecl->setIvarLBraceLoc(LBrac);
19010  IMPDecl->setIvarRBraceLoc(RBrac);
19011  } else if (ObjCCategoryDecl *CDecl =
19012  dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19013  // case of ivars in class extension; all other cases have been
19014  // reported as errors elsewhere.
19015  // FIXME. Class extension does not have a LocEnd field.
19016  // CDecl->setLocEnd(RBrac);
19017  // Add ivar's to class extension's DeclContext.
19018  // Diagnose redeclaration of private ivars.
19019  ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19020  for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19021  if (IDecl) {
19022  if (const ObjCIvarDecl *ClsIvar =
19023  IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19024  Diag(ClsFields[i]->getLocation(),
19025  diag::err_duplicate_ivar_declaration);
19026  Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19027  continue;
19028  }
19029  for (const auto *Ext : IDecl->known_extensions()) {
19030  if (const ObjCIvarDecl *ClsExtIvar
19031  = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19032  Diag(ClsFields[i]->getLocation(),
19033  diag::err_duplicate_ivar_declaration);
19034  Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19035  continue;
19036  }
19037  }
19038  }
19039  ClsFields[i]->setLexicalDeclContext(CDecl);
19040  CDecl->addDecl(ClsFields[i]);
19041  }
19042  CDecl->setIvarLBraceLoc(LBrac);
19043  CDecl->setIvarRBraceLoc(RBrac);
19044  }
19045  }
19046 }
19047 
19048 /// Determine whether the given integral value is representable within
19049 /// the given type T.
19052  QualType T) {
19053  assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19054  "Integral type required!");
19055  unsigned BitWidth = Context.getIntWidth(T);
19056 
19057  if (Value.isUnsigned() || Value.isNonNegative()) {
19059  --BitWidth;
19060  return Value.getActiveBits() <= BitWidth;
19061  }
19062  return Value.getMinSignedBits() <= BitWidth;
19063 }
19064 
19065 // Given an integral type, return the next larger integral type
19066 // (or a NULL type of no such type exists).
19068  // FIXME: Int128/UInt128 support, which also needs to be introduced into
19069  // enum checking below.
19070  assert((T->isIntegralType(Context) ||
19071  T->isEnumeralType()) && "Integral type required!");
19072  const unsigned NumTypes = 4;
19073  QualType SignedIntegralTypes[NumTypes] = {
19074  Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19075  };
19076  QualType UnsignedIntegralTypes[NumTypes] = {
19077  Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19078  Context.UnsignedLongLongTy
19079  };
19080 
19081  unsigned BitWidth = Context.getTypeSize(T);
19082  QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19083  : UnsignedIntegralTypes;
19084  for (unsigned I = 0; I != NumTypes; ++I)
19085  if (Context.getTypeSize(Types[I]) > BitWidth)
19086  return Types[I];
19087 
19088  return QualType();
19089 }
19090 
19092  EnumConstantDecl *LastEnumConst,
19093  SourceLocation IdLoc,
19094  IdentifierInfo *Id,
19095  Expr *Val) {
19096  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19097  llvm::APSInt EnumVal(IntWidth);
19098  QualType EltTy;
19099 
19100  if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
19101  Val = nullptr;
19102 
19103  if (Val)
19104  Val = DefaultLvalueConversion(Val).get();
19105 
19106  if (Val) {
19107  if (Enum->isDependentType() || Val->isTypeDependent() ||
19108  Val->containsErrors())
19109  EltTy = Context.DependentTy;
19110  else {
19111  // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19112  // underlying type, but do allow it in all other contexts.
19113  if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19114  // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19115  // constant-expression in the enumerator-definition shall be a converted
19116  // constant expression of the underlying type.
19117  EltTy = Enum->getIntegerType();
19118  ExprResult Converted =
19119  CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19120  CCEK_Enumerator);
19121  if (Converted.isInvalid())
19122  Val = nullptr;
19123  else
19124  Val = Converted.get();
19125  } else if (!Val->isValueDependent() &&
19126  !(Val =
19127  VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
19128  .get())) {
19129  // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19130  } else {
19131  if (Enum->isComplete()) {
19132  EltTy = Enum->getIntegerType();
19133 
19134  // In Obj-C and Microsoft mode, require the enumeration value to be
19135  // representable in the underlying type of the enumeration. In C++11,
19136  // we perform a non-narrowing conversion as part of converted constant
19137  // expression checking.
19138  if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19139  if (Context.getTargetInfo()
19140  .getTriple()
19141  .isWindowsMSVCEnvironment()) {
19142  Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19143  } else {
19144  Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19145  }
19146  }
19147 
19148  // Cast to the underlying type.
19149  Val = ImpCastExprToType(Val, EltTy,
19150  EltTy->isBooleanType() ? CK_IntegralToBoolean
19151  : CK_IntegralCast)
19152  .get();
19153  } else if (getLangOpts().CPlusPlus) {
19154  // C++11 [dcl.enum]p5:
19155  // If the underlying type is not fixed, the type of each enumerator
19156  // is the type of its initializing value:
19157  // - If an initializer is specified for an enumerator, the
19158  // initializing value has the same type as the expression.
19159  EltTy = Val->getType();
19160  } else {
19161  // C99 6.7.2.2p2:
19162  // The expression that defines the value of an enumeration constant
19163  // shall be an integer constant expression that has a value
19164  // representable as an int.
19165 
19166  // Complain if the value is not representable in an int.
19167  if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
19168  Diag(IdLoc, diag::ext_enum_value_not_int)
19169  << toString(EnumVal, 10) << Val->getSourceRange()
19170  << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19171  else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19172  // Force the type of the expression to 'int'.
19173  Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19174  }
19175  EltTy = Val->getType();
19176  }
19177  }
19178  }
19179  }
19180 
19181  if (!Val) {
19182  if (Enum->isDependentType())
19183  EltTy = Context.DependentTy;
19184  else if (!LastEnumConst) {
19185  // C++0x [dcl.enum]p5:
19186  // If the underlying type is not fixed, the type of each enumerator
19187  // is the type of its initializing value:
19188  // - If no initializer is specified for the first enumerator, the
19189  // initializing value has an unspecified integral type.
19190  //
19191  // GCC uses 'int' for its unspecified integral type, as does
19192  // C99 6.7.2.2p3.
19193  if (Enum->isFixed()) {
19194  EltTy = Enum->getIntegerType();
19195  }
19196  else {
19197  EltTy = Context.IntTy;
19198  }
19199  } else {
19200  // Assign the last value + 1.
19201  EnumVal = LastEnumConst->getInitVal();
19202  ++EnumVal;
19203  EltTy = LastEnumConst->getType();
19204 
19205  // Check for overflow on increment.
19206  if (EnumVal < LastEnumConst->getInitVal()) {
19207  // C++0x [dcl.enum]p5:
19208  // If the underlying type is not fixed, the type of each enumerator
19209  // is the type of its initializing value:
19210  //
19211  // - Otherwise the type of the initializing value is the same as
19212  // the type of the initializing value of the preceding enumerator
19213  // unless the incremented value is not representable in that type,
19214  // in which case the type is an unspecified integral type
19215  // sufficient to contain the incremented value. If no such type
19216  // exists, the program is ill-formed.
19217  QualType T = getNextLargerIntegralType(Context, EltTy);
19218  if (T.isNull() || Enum->isFixed()) {
19219  // There is no integral type larger enough to represent this
19220  // value. Complain, then allow the value to wrap around.
19221  EnumVal = LastEnumConst->getInitVal();
19222  EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19223  ++EnumVal;
19224  if (Enum->isFixed())
19225  // When the underlying type is fixed, this is ill-formed.
19226  Diag(IdLoc, diag::err_enumerator_wrapped)
19227  << toString(EnumVal, 10)
19228  << EltTy;
19229  else
19230  Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19231  << toString(EnumVal, 10);
19232  } else {
19233  EltTy = T;
19234  }
19235 
19236  // Retrieve the last enumerator's value, extent that type to the
19237  // type that is supposed to be large enough to represent the incremented
19238  // value, then increment.
19239  EnumVal = LastEnumConst->getInitVal();
19240  EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19241  EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19242  ++EnumVal;
19243 
19244  // If we're not in C++, diagnose the overflow of enumerator values,
19245  // which in C99 means that the enumerator value is not representable in
19246  // an int (C99 6.7.2.2p2). However, we support GCC's extension that
19247  // permits enumerator values that are representable in some larger
19248  // integral type.
19249  if (!getLangOpts().CPlusPlus && !T.isNull())
19250  Diag(IdLoc, diag::warn_enum_value_overflow);
19251  } else if (!getLangOpts().CPlusPlus &&
19252  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19253  // Enforce C99 6.7.2.2p2 even when we compute the next value.
19254  Diag(IdLoc, diag::ext_enum_value_not_int)
19255  << toString(EnumVal, 10) << 1;
19256  }
19257  }
19258  }
19259 
19260  if (!EltTy->isDependentType()) {
19261  // Make the enumerator value match the signedness and size of the
19262  // enumerator's type.
19263  EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19264  EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19265  }
19266 
19267  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19268  Val, EnumVal);
19269 }
19270 
19272  SourceLocation IILoc) {
19273  if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
19274  !getLangOpts().CPlusPlus)
19275  return SkipBodyInfo();
19276 
19277  // We have an anonymous enum definition. Look up the first enumerator to
19278  // determine if we should merge the definition with an existing one and
19279  // skip the body.
19280  NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
19281  forRedeclarationInCurContext());
19282  auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
19283  if (!PrevECD)
19284  return SkipBodyInfo();
19285 
19286  EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19287  NamedDecl *Hidden;
19288  if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19289  SkipBodyInfo Skip;
19290  Skip.Previous = Hidden;
19291  return Skip;
19292  }
19293 
19294  return SkipBodyInfo();
19295 }
19296 
19297 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19299  const ParsedAttributesView &Attrs,
19300  SourceLocation EqualLoc, Expr *Val) {
19301  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
19302  EnumConstantDecl *LastEnumConst =
19303  cast_or_null<EnumConstantDecl>(lastEnumConst);
19304 
19305  // The scope passed in may not be a decl scope. Zip up the scope tree until
19306  // we find one that is.
19307  S = getNonFieldDeclScope(S);
19308 
19309  // Verify that there isn't already something declared with this name in this
19310  // scope.
19311  LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
19312  LookupName(R, S);
19313  NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19314 
19315  if (PrevDecl && PrevDecl->isTemplateParameter()) {
19316  // Maybe we will complain about the shadowed template parameter.
19317  DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19318  // Just pretend that we didn't see the previous declaration.
19319  PrevDecl = nullptr;
19320  }
19321 
19322  // C++ [class.mem]p15:
19323  // If T is the name of a class, then each of the following shall have a name
19324  // different from T:
19325  // - every enumerator of every member of class T that is an unscoped
19326  // enumerated type
19327  if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19328  DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
19329  DeclarationNameInfo(Id, IdLoc));
19330 
19331  EnumConstantDecl *New =
19332  CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19333  if (!New)
19334  return nullptr;
19335 
19336  if (PrevDecl) {
19337  if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
19338  // Check for other kinds of shadowing not already handled.
19339  CheckShadow(New, PrevDecl, R);
19340  }
19341 
19342  // When in C++, we may get a TagDecl with the same name; in this case the
19343  // enum constant will 'hide' the tag.
19344  assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
19345  "Received TagDecl when not in C++!");
19346  if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
19347  if (isa<EnumConstantDecl>(PrevDecl))
19348  Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19349  else
19350  Diag(IdLoc, diag::err_redefinition) << Id;
19351  notePreviousDefinition(PrevDecl, IdLoc);
19352  return nullptr;
19353  }
19354  }
19355 
19356  // Process attributes.
19357  ProcessDeclAttributeList(S, New, Attrs);
19358  AddPragmaAttributes(S, New);
19359 
19360  // Register this decl in the current scope stack.
19361  New->setAccess(TheEnumDecl->getAccess());
19362  PushOnScopeChains(New, S);
19363 
19364  ActOnDocumentableDecl(New);
19365 
19366  return New;
19367 }
19368 
19369 // Returns true when the enum initial expression does not trigger the
19370 // duplicate enum warning. A few common cases are exempted as follows:
19371 // Element2 = Element1
19372 // Element2 = Element1 + 1
19373 // Element2 = Element1 - 1
19374 // Where Element2 and Element1 are from the same enum.
19376  Expr *InitExpr = ECD->getInitExpr();
19377  if (!InitExpr)
19378  return true;
19379  InitExpr = InitExpr->IgnoreImpCasts();
19380 
19381  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
19382  if (!BO->isAdditiveOp())
19383  return true;
19384  IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19385  if (!IL)
19386  return true;
19387  if (IL->getValue() != 1)
19388  return true;
19389 
19390  InitExpr = BO->getLHS();
19391  }
19392 
19393  // This checks if the elements are from the same enum.
19394  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
19395  if (!DRE)
19396  return true;
19397 
19398  EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19399  if (!EnumConstant)
19400  return true;
19401 
19402  if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19403  Enum)
19404  return true;
19405 
19406  return false;
19407 }
19408 
19409 // Emits a warning when an element is implicitly set a value that
19410 // a previous element has already been set to.
19412  EnumDecl *Enum, QualType EnumType) {
19413  // Avoid anonymous enums
19414  if (!Enum->getIdentifier())
19415  return;
19416 
19417  // Only check for small enums.
19418  if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
19419  return;
19420 
19421  if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19422  return;
19423 
19424  typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
19425  typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
19426 
19427  typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
19428 
19429  // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19430  typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
19431 
19432  // Use int64_t as a key to avoid needing special handling for map keys.
19433  auto EnumConstantToKey = [](const EnumConstantDecl *D) {
19434  llvm::APSInt Val = D->getInitVal();
19435  return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
19436  };
19437 
19438  DuplicatesVector DupVector;
19439  ValueToVectorMap EnumMap;
19440 
19441  // Populate the EnumMap with all values represented by enum constants without
19442  // an initializer.
19443  for (auto *Element : Elements) {
19444  EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
19445 
19446  // Null EnumConstantDecl means a previous diagnostic has been emitted for
19447  // this constant. Skip this enum since it may be ill-formed.
19448  if (!ECD) {
19449  return;
19450  }
19451 
19452  // Constants with initalizers are handled in the next loop.
19453  if (ECD->getInitExpr())
19454  continue;
19455 
19456  // Duplicate values are handled in the next loop.
19457  EnumMap.insert({EnumConstantToKey(ECD), ECD});
19458  }
19459 
19460  if (EnumMap.size() == 0)
19461  return;
19462 
19463  // Create vectors for any values that has duplicates.
19464  for (auto *Element : Elements) {
19465  // The last loop returned if any constant was null.
19466  EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
19467  if (!ValidDuplicateEnum(ECD, Enum))
19468  continue;
19469 
19470  auto Iter = EnumMap.find(EnumConstantToKey(ECD));
19471  if (Iter == EnumMap.end())
19472  continue;
19473 
19474  DeclOrVector& Entry = Iter->second;
19475  if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
19476  // Ensure constants are different.
19477  if (D == ECD)
19478  continue;
19479 
19480  // Create new vector and push values onto it.
19481  auto Vec = std::make_unique<ECDVector>();
19482  Vec->push_back(D);
19483  Vec->push_back(ECD);
19484 
19485  // Update entry to point to the duplicates vector.
19486  Entry = Vec.get();
19487 
19488  // Store the vector somewhere we can consult later for quick emission of
19489  // diagnostics.
19490  DupVector.emplace_back(std::move(Vec));
19491  continue;
19492  }
19493 
19494  ECDVector *Vec = Entry.get<ECDVector*>();
19495  // Make sure constants are not added more than once.
19496  if (*Vec->begin() == ECD)
19497  continue;
19498 
19499  Vec->push_back(ECD);
19500  }
19501 
19502  // Emit diagnostics.
19503  for (const auto &Vec : DupVector) {
19504  assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
19505 
19506  // Emit warning for one enum constant.
19507  auto *FirstECD = Vec->front();
19508  S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
19509  << FirstECD << toString(FirstECD->getInitVal(), 10)
19510  << FirstECD->getSourceRange();
19511 
19512  // Emit one note for each of the remaining enum constants with
19513  // the same value.
19514  for (auto *ECD : llvm::drop_begin(*Vec))
19515  S.Diag(ECD->getLocation(), diag::note_duplicate_element)
19516  << ECD << toString(ECD->getInitVal(), 10)
19517  << ECD->getSourceRange();
19518  }
19519 }
19520 
19521 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
19522  bool AllowMask) const {
19523  assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
19524  assert(ED->isCompleteDefinition() && "expected enum definition");
19525 
19526  auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
19527  llvm::APInt &FlagBits = R.first->second;
19528 
19529  if (R.second) {
19530  for (auto *E : ED->enumerators()) {
19531  const auto &EVal = E->getInitVal();
19532  // Only single-bit enumerators introduce new flag values.
19533  if (EVal.isPowerOf2())
19534  FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
19535  }
19536  }
19537 
19538  // A value is in a flag enum if either its bits are a subset of the enum's
19539  // flag bits (the first condition) or we are allowing masks and the same is
19540  // true of its complement (the second condition). When masks are allowed, we
19541  // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
19542  //
19543  // While it's true that any value could be used as a mask, the assumption is
19544  // that a mask will have all of the insignificant bits set. Anything else is
19545  // likely a logic error.
19546  llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
19547  return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
19548 }
19549 
19551  Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
19552  const ParsedAttributesView &Attrs) {
19553  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
19554  QualType EnumType = Context.getTypeDeclType(Enum);
19555 
19556  ProcessDeclAttributeList(S, Enum, Attrs);
19557 
19558  if (Enum->isDependentType()) {
19559  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19560  EnumConstantDecl *ECD =
19561  cast_or_null<EnumConstantDecl>(Elements[i]);
19562  if (!ECD) continue;
19563 
19564  ECD->setType(EnumType);
19565  }
19566 
19567  Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
19568  return;
19569  }
19570 
19571  // TODO: If the result value doesn't fit in an int, it must be a long or long
19572  // long value. ISO C does not support this, but GCC does as an extension,
19573  // emit a warning.
19574  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19575  unsigned CharWidth = Context.getTargetInfo().getCharWidth();
19576  unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
19577 
19578  // Verify that all the values are okay, compute the size of the values, and
19579  // reverse the list.
19580  unsigned NumNegativeBits = 0;
19581  unsigned NumPositiveBits = 0;
19582 
19583  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19584  EnumConstantDecl *ECD =
19585  cast_or_null<EnumConstantDecl>(Elements[i]);
19586  if (!ECD) continue; // Already issued a diagnostic.
19587 
19588  const llvm::APSInt &InitVal = ECD->getInitVal();
19589 
19590  // Keep track of the size of positive and negative values.
19591  if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
19592  // If the enumerator is zero that should still be counted as a positive
19593  // bit since we need a bit to store the value zero.
19594  unsigned ActiveBits = InitVal.getActiveBits();
19595  NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
19596  } else {
19597  NumNegativeBits = std::max(NumNegativeBits,
19598  (unsigned)InitVal.getMinSignedBits());
19599  }
19600  }
19601 
19602  // If we have an empty set of enumerators we still need one bit.
19603  // From [dcl.enum]p8
19604  // If the enumerator-list is empty, the values of the enumeration are as if
19605  // the enumeration had a single enumerator with value 0
19606  if (!NumPositiveBits && !NumNegativeBits)
19607  NumPositiveBits = 1;
19608 
19609  // Figure out the type that should be used for this enum.
19610  QualType BestType;
19611  unsigned BestWidth;
19612 
19613  // C++0x N3000 [conv.prom]p3:
19614  // An rvalue of an unscoped enumeration type whose underlying
19615  // type is not fixed can be converted to an rvalue of the first
19616  // of the following types that can represent all the values of
19617  // the enumeration: int, unsigned int, long int, unsigned long
19618  // int, long long int, or unsigned long long int.
19619  // C99 6.4.4.3p2:
19620  // An identifier declared as an enumeration constant has type int.
19621  // The C99 rule is modified by a gcc extension
19622  QualType BestPromotionType;
19623 
19624  bool Packed = Enum->hasAttr<PackedAttr>();
19625  // -fshort-enums is the equivalent to specifying the packed attribute on all
19626  // enum definitions.
19627  if (LangOpts.ShortEnums)
19628  Packed = true;
19629 
19630  // If the enum already has a type because it is fixed or dictated by the
19631  // target, promote that type instead of analyzing the enumerators.
19632  if (Enum->isComplete()) {
19633  BestType = Enum->getIntegerType();
19634  if (Context.isPromotableIntegerType(BestType))
19635  BestPromotionType = Context.getPromotedIntegerType(BestType);
19636  else
19637  BestPromotionType = BestType;
19638 
19639  BestWidth = Context.getIntWidth(BestType);
19640  }
19641  else if (NumNegativeBits) {
19642  // If there is a negative value, figure out the smallest integer type (of
19643  // int/long/longlong) that fits.
19644  // If it's packed, check also if it fits a char or a short.
19645  if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
19646  BestType = Context.SignedCharTy;
19647  BestWidth = CharWidth;
19648  } else if (Packed && NumNegativeBits <= ShortWidth &&
19649  NumPositiveBits < ShortWidth) {
19650  BestType = Context.ShortTy;
19651  BestWidth = ShortWidth;
19652  } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
19653  BestType = Context.IntTy;
19654  BestWidth = IntWidth;
19655  } else {
19656  BestWidth = Context.getTargetInfo().getLongWidth();
19657 
19658  if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
19659  BestType = Context.LongTy;
19660  } else {
19661  BestWidth = Context.getTargetInfo().getLongLongWidth();
19662 
19663  if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
19664  Diag(Enum->getLocation(), diag::ext_enum_too_large);
19665  BestType = Context.LongLongTy;
19666  }
19667  }
19668  BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
19669  } else {
19670  // If there is no negative value, figure out the smallest type that fits
19671  // all of the enumerator values.
19672  // If it's packed, check also if it fits a char or a short.
19673  if (Packed && NumPositiveBits <= CharWidth) {
19674  BestType = Context.UnsignedCharTy;
19675  BestPromotionType = Context.IntTy;
19676  BestWidth = CharWidth;
19677  } else if (Packed && NumPositiveBits <= ShortWidth) {
19678  BestType = Context.UnsignedShortTy;
19679  BestPromotionType = Context.IntTy;
19680  BestWidth = ShortWidth;
19681  } else if (NumPositiveBits <= IntWidth) {
19682  BestType = Context.UnsignedIntTy;
19683  BestWidth = IntWidth;
19684  BestPromotionType
19685  = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19686  ? Context.UnsignedIntTy : Context.IntTy;
19687  } else if (NumPositiveBits <=
19688  (BestWidth = Context.getTargetInfo().getLongWidth())) {
19689  BestType = Context.UnsignedLongTy;
19690  BestPromotionType
19691  = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19692  ? Context.UnsignedLongTy : Context.LongTy;
19693  } else {
19694  BestWidth = Context.getTargetInfo().getLongLongWidth();
19695  assert(NumPositiveBits <= BestWidth &&
19696  "How could an initializer get larger than ULL?");
19697  BestType = Context.UnsignedLongLongTy;
19698  BestPromotionType
19699  = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19700  ? Context.UnsignedLongLongTy : Context.LongLongTy;
19701  }
19702  }
19703 
19704  // Loop over all of the enumerator constants, changing their types to match
19705  // the type of the enum if needed.
19706  for (auto *D : Elements) {
19707  auto *ECD = cast_or_null<EnumConstantDecl>(D);
19708  if (!ECD) continue; // Already issued a diagnostic.
19709 
19710  // Standard C says the enumerators have int type, but we allow, as an
19711  // extension, the enumerators to be larger than int size. If each
19712  // enumerator value fits in an int, type it as an int, otherwise type it the
19713  // same as the enumerator decl itself. This means that in "enum { X = 1U }"
19714  // that X has type 'int', not 'unsigned'.
19715 
19716  // Determine whether the value fits into an int.
19717  llvm::APSInt InitVal = ECD->getInitVal();
19718 
19719  // If it fits into an integer type, force it. Otherwise force it to match
19720  // the enum decl type.
19721  QualType NewTy;
19722  unsigned NewWidth;
19723  bool NewSign;
19724  if (!getLangOpts().CPlusPlus &&
19725  !Enum->isFixed() &&
19726  isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
19727  NewTy = Context.IntTy;
19728  NewWidth = IntWidth;
19729  NewSign = true;
19730  } else if (ECD->getType() == BestType) {
19731  // Already the right type!
19732  if (getLangOpts().CPlusPlus)
19733  // C++ [dcl.enum]p4: Following the closing brace of an
19734  // enum-specifier, each enumerator has the type of its
19735  // enumeration.
19736  ECD->setType(EnumType);
19737  continue;
19738  } else {
19739  NewTy = BestType;
19740  NewWidth = BestWidth;
19741  NewSign = BestType->isSignedIntegerOrEnumerationType();
19742  }
19743 
19744  // Adjust the APSInt value.
19745  InitVal = InitVal.extOrTrunc(NewWidth);
19746  InitVal.setIsSigned(NewSign);
19747  ECD->setInitVal(InitVal);
19748 
19749  // Adjust the Expr initializer and type.
19750  if (ECD->getInitExpr() &&
19751  !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
19752  ECD->setInitExpr(ImplicitCastExpr::Create(
19753  Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
19754  /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
19755  if (getLangOpts().CPlusPlus)
19756  // C++ [dcl.enum]p4: Following the closing brace of an
19757  // enum-specifier, each enumerator has the type of its
19758  // enumeration.
19759  ECD->setType(EnumType);
19760  else
19761  ECD->setType(NewTy);
19762  }
19763 
19764  Enum->completeDefinition(BestType, BestPromotionType,
19765  NumPositiveBits, NumNegativeBits);
19766 
19767  CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
19768 
19769  if (Enum->isClosedFlag()) {
19770  for (Decl *D : Elements) {
19771  EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
19772  if (!ECD) continue; // Already issued a diagnostic.
19773 
19774  llvm::APSInt InitVal = ECD->getInitVal();
19775  if (InitVal != 0 && !InitVal.isPowerOf2() &&
19776  !IsValueInFlagEnum(Enum, InitVal, true))
19777  Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
19778  << ECD << Enum;
19779  }
19780  }
19781 
19782  // Now that the enum type is defined, ensure it's not been underaligned.
19783  if (Enum->hasAttrs())
19784  CheckAlignasUnderalignment(Enum);
19785 }
19786 
19788  SourceLocation StartLoc,
19789  SourceLocation EndLoc) {
19790  StringLiteral *AsmString = cast<StringLiteral>(expr);
19791 
19792  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
19793  AsmString, StartLoc,
19794  EndLoc);
19795  CurContext->addDecl(New);
19796  return New;
19797 }
19798 
19800  auto *New = TopLevelStmtDecl::Create(Context, Statement);
19801  Context.getTranslationUnitDecl()->addDecl(New);
19802  return New;
19803 }
19804 
19806  IdentifierInfo* AliasName,
19807  SourceLocation PragmaLoc,
19808  SourceLocation NameLoc,
19809  SourceLocation AliasNameLoc) {
19810  NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
19811  LookupOrdinaryName);
19812  AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
19814  AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
19815  Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
19816 
19817  // If a declaration that:
19818  // 1) declares a function or a variable
19819  // 2) has external linkage
19820  // already exists, add a label attribute to it.
19821  if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19822  if (isDeclExternC(PrevDecl))
19823  PrevDecl->addAttr(Attr);
19824  else
19825  Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
19826  << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
19827  // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
19828  } else
19829  (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
19830 }
19831 
19833  SourceLocation PragmaLoc,
19834  SourceLocation NameLoc) {
19835  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
19836 
19837  if (PrevDecl) {
19838  PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
19839  } else {
19840  (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
19841  }
19842 }
19843 
19845  IdentifierInfo* AliasName,
19846  SourceLocation PragmaLoc,
19847  SourceLocation NameLoc,
19848  SourceLocation AliasNameLoc) {
19849  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
19850  LookupOrdinaryName);
19851  WeakInfo W = WeakInfo(Name, NameLoc);
19852 
19853  if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19854  if (!PrevDecl->hasAttr<AliasAttr>())
19855  if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
19856  DeclApplyPragmaWeak(TUScope, ND, W);
19857  } else {
19858  (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
19859  }
19860 }
19861 
19863  return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
19864 }
19865 
19867  bool Final) {
19868  assert(FD && "Expected non-null FunctionDecl");
19869 
19870  // SYCL functions can be template, so we check if they have appropriate
19871  // attribute prior to checking if it is a template.
19872  if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
19873  return FunctionEmissionStatus::Emitted;
19874 
19875  // Templates are emitted when they're instantiated.
19876  if (FD->isDependentContext())
19877  return FunctionEmissionStatus::TemplateDiscarded;
19878 
19879  // Check whether this function is an externally visible definition.
19880  auto IsEmittedForExternalSymbol = [this, FD]() {
19881  // We have to check the GVA linkage of the function's *definition* -- if we
19882  // only have a declaration, we don't know whether or not the function will
19883  // be emitted, because (say) the definition could include "inline".
19884  FunctionDecl *Def = FD->getDefinition();
19885 
19886  return Def && !isDiscardableGVALinkage(
19887  getASTContext().GetGVALinkageForFunction(Def));
19888  };
19889 
19890  if (LangOpts.OpenMPIsDevice) {
19891  // In OpenMP device mode we will not emit host only functions, or functions
19892  // we don't need due to their linkage.
19893  std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19894  OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19895  // DevTy may be changed later by
19896  // #pragma omp declare target to(*) device_type(*).
19897  // Therefore DevTy having no value does not imply host. The emission status
19898  // will be checked again at the end of compilation unit with Final = true.
19899  if (DevTy)
19900  if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
19901  return FunctionEmissionStatus::OMPDiscarded;
19902  // If we have an explicit value for the device type, or we are in a target
19903  // declare context, we need to emit all extern and used symbols.
19904  if (isInOpenMPDeclareTargetContext() || DevTy)
19905  if (IsEmittedForExternalSymbol())
19906  return FunctionEmissionStatus::Emitted;
19907  // Device mode only emits what it must, if it wasn't tagged yet and needed,
19908  // we'll omit it.
19909  if (Final)
19910  return FunctionEmissionStatus::OMPDiscarded;
19911  } else if (LangOpts.OpenMP > 45) {
19912  // In OpenMP host compilation prior to 5.0 everything was an emitted host
19913  // function. In 5.0, no_host was introduced which might cause a function to
19914  // be ommitted.
19915  std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19916  OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19917  if (DevTy)
19918  if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
19919  return FunctionEmissionStatus::OMPDiscarded;
19920  }
19921 
19922  if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
19923  return FunctionEmissionStatus::Emitted;
19924 
19925  if (LangOpts.CUDA) {
19926  // When compiling for device, host functions are never emitted. Similarly,
19927  // when compiling for host, device and global functions are never emitted.
19928  // (Technically, we do emit a host-side stub for global functions, but this
19929  // doesn't count for our purposes here.)
19930  Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
19931  if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
19932  return FunctionEmissionStatus::CUDADiscarded;
19933  if (!LangOpts.CUDAIsDevice &&
19934  (T == Sema::CFT_Device || T == Sema::CFT_Global))
19935  return FunctionEmissionStatus::CUDADiscarded;
19936 
19937  if (IsEmittedForExternalSymbol())
19938  return FunctionEmissionStatus::Emitted;
19939  }
19940 
19941  // Otherwise, the function is known-emitted if it's in our set of
19942  // known-emitted functions.
19944 }
19945 
19947  // Host-side references to a __global__ function refer to the stub, so the
19948  // function itself is never emitted and therefore should not be marked.
19949  // If we have host fn calls kernel fn calls host+device, the HD function
19950  // does not get instantiated on the host. We model this by omitting at the
19951  // call to the kernel from the callgraph. This ensures that, when compiling
19952  // for host, only HD functions actually called from the host get marked as
19953  // known-emitted.
19954  return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
19955  IdentifyCUDATarget(Callee) == CFT_Global;
19956 }
clang::OpenCL
@ OpenCL
Definition: LangStandard.h:62
clang::Type::isIntegralType
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1954
clang::Decl::setLexicalDeclContext
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:340
diagnoseMissingConstinit
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, const ConstInitAttr *CIAttr, bool AttrBeforeInit)
Definition: SemaDecl.cpp:3115
clang::QualifierCollector::strip
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:6582
clang::BuiltinType
This class is used for builtin types like 'int'.
Definition: Type.h:2627
diagnoseImplicitlyRetainedSelf
static void diagnoseImplicitlyRetainedSelf(Sema &S)
Definition: SemaDecl.cpp:15390
clang::FunctionDecl::getSourceRange
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4138
clang::FunctionDefinitionKind::Defaulted
@ Defaulted
hasDeducedAuto
static bool hasDeducedAuto(DeclaratorDecl *DD)
Definition: SemaDecl.cpp:14407
clang::DeclaratorDecl::getInnerLocStart
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:810
clang::NestedNameSpecifier::Create
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
Definition: NestedNameSpecifier.cpp:59
clang::ExplicitSpecifier
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1842
clang::DeclarationNameInfo::setCXXLiteralOperatorNameLoc
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
Definition: DeclarationName.h:850
clang::EnumDecl::setIntegerTypeSourceInfo
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition: Decl.h:3890
clang::CXXMethodDecl::getThisType
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2502
clang::Sema::CheckShadow
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:8180
clang::DeclSpec::getVirtualSpecLoc
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:599
clang::InternalLinkage
@ InternalLinkage
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:31
clang::TagDecl::hasNameForLinkage
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3660
clang::Language::CUDA
@ CUDA
clang::DeclaratorChunk::FunctionTypeInfo::NumParams
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1338
clang::ObjCInterfaceDecl
Represents an ObjC class declaration.
Definition: DeclObjC.h:1146
clang::UnqualifiedId
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:973
clang::RecordDecl::hasFlexibleArrayMember
bool hasFlexibleArrayMember() const
Definition: Decl.h:4051
clang::FunctionNoProtoTypeLoc
Definition: TypeLoc.h:1504
clang::ASTContext::getTypeSizeInChars
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
Definition: ASTContext.cpp:2560
clang::FunctionDecl::getMultiVersionKind
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition: Decl.cpp:3352
clang::VarDecl::TentativeDefinition
@ TentativeDefinition
This declaration is a tentative definition.
Definition: Decl.h:1257
clang::Type::getObjCARCImplicitLifetime
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:4384
clang::Sema::CurContext
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:421
clang::Type::isSamplerT
bool isSamplerT() const
Definition: Type.h:7089
clang::ReturnStmt::setNRVOCandidate
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition: Stmt.h:2854
clang::ASTContext::getQualifiedType
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2111
Builtins.h
clang::DeclaratorChunk::FunctionTypeInfo::hasPrototype
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition: DeclSpec.h:1303
clang::ParenTypeLoc::getInnerLoc
TypeLoc getInnerLoc() const
Definition: TypeLoc.h:1174
clang::FunctionDecl::doesThisDeclarationHaveABody
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:2230
clang::Declarator::getName
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:1988
clang::DeclaratorChunk::getReference
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition: DeclSpec.h:1620
clang::Type::isRecordType
bool isRecordType() const
Definition: Type.h:6986
clang::QualType::DK_nontrivial_c_struct
@ DK_nontrivial_c_struct
Definition: Type.h:1281
clang::LangAS::opencl_private
@ opencl_private
clang::ObjCCompatibleAliasDecl
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition: DeclObjC.h:2759
clang::Module::getTopLevelModule
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition: Module.h:597
isAcceptableTagRedeclContext
static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, DeclContext *NewDC)
Determine whether a tag originally declared in context OldDC can be redeclared with an unqualified na...
Definition: SemaDecl.cpp:16587
clang::FunctionTemplateDecl::mergePrevDecl
void mergePrevDecl(FunctionTemplateDecl *Prev)
Merge Prev with our RedeclarableTemplateDecl::Common.
Definition: DeclTemplate.cpp:422
clang::OpaquePtr::get
PtrTy get() const
Definition: Ownership.h:80
clang::MangleNumberingContext::getManglingNumber
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
max
__DEVICE__ int max(int __a, int __b)
Definition: __clang_cuda_math.h:196
clang::Sema::getNonFieldDeclScope
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
Definition: SemaDecl.cpp:2351
clang::sema::Capture::getLocation
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:657
clang::isLambdaCallOperator
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
clang::Sema::diagnoseQualifiedDeclaration
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, bool IsTemplateId)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
Definition: SemaDecl.cpp:6134
clang::LookupResult::NotFound
@ NotFound
No entity found met the criteria.
Definition: Lookup.h:50
clang::FunctionDecl::isDefaulted
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2282
clang::QualType::getObjCLifetime
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1194
clang::Sema::DelayedDiagnostics
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition: Sema.h:948
clang::RecordDecl::field_begin
field_iterator field_begin() const
Definition: Decl.cpp:4762
clang::InitializationKind::CreateForInit
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
Definition: Initialization.h:697
clang::isGenericLambdaCallOperatorSpecialization
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:38
AllowOverloadingOfFunction
static bool AllowOverloadingOfFunction(const LookupResult &Previous, ASTContext &Context, const FunctionDecl *New)
Determine whether overloading is allowed for a new function declaration considering prior declaration...
Definition: SemaDecl.cpp:1510
isClassCompatTagKind
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class,...
Definition: SemaDecl.cpp:16387
clang::SourceManager::getFilename
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
Definition: SourceManager.cpp:1020
clang::DeclContext::removeDecl
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1526
clang::Sema::RebuildNestedNameSpecifierInCurrentInstantiation
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
Definition: SemaTemplate.cpp:11202
IsDisallowedCopyOrAssign
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
Definition: SemaDecl.cpp:1841
clang::Type::isOpenCLSpecificType
bool isOpenCLSpecificType() const
Definition: Type.h:7145
clang::RecordDecl::setHasNonTrivialToPrimitiveCopyCUnion
void setHasNonTrivialToPrimitiveCopyCUnion(bool V)
Definition: Decl.h:4140
clang::FunctionDecl::setRangeEnd
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2124
clang::FunctionDecl::hasWrittenPrototype
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition: Decl.h:2345
clang::CXXConstructorDecl
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2448
clang::ASTContext::getTypeDeclType
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1554
clang::RecordDecl::hasVolatileMember
bool hasVolatileMember() const
Definition: Decl.h:4081
clang::CXXMethodDecl::isCopyAssignmentOperator
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2410
clang::QualType::hasNonTrivialToPrimitiveCopyCUnion
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition: Type.h:6790
clang::TypoCorrection::begin
decl_iterator begin()
Definition: TypoCorrection.h:232
clang::VarDecl::getSourceRange
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2118
clang::Decl::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:424
clang::Decl::isUnavailable
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition: DeclBase.h:729
clang::TypoCorrection::const_decl_iterator
SmallVectorImpl< NamedDecl * >::const_iterator const_decl_iterator
Definition: TypoCorrection.h:238
clang::TypoCorrection::decl_iterator
SmallVectorImpl< NamedDecl * >::iterator decl_iterator
Definition: TypoCorrection.h:230
clang::Sema::DiagnoseUnusedNestedTypedefs
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
Definition: SemaDecl.cpp:2096
mergeDeclAttribute
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, Sema::AvailabilityMergeKind AMK)
Definition: SemaDecl.cpp:2875
getTagInjectionScope
static Scope * getTagInjectionScope(Scope *S, const LangOptions &LangOpts)
Find the Scope in which a tag is implicitly declared if we see an elaborated type specifier in the sp...
Definition: SemaDecl.cpp:9538
clang::AttributePool::getFactory
AttributeFactory & getFactory() const
Definition: ParsedAttr.h:826
TypeLocBuilder.h
clang::FunctionDecl::getNumParams
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3473
clang::Type::isBlockPointerType
bool isBlockPointerType() const
Definition: Type.h:6904
clang::ASTContext::hasDirectOwnershipQualifier
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
Definition: ASTContext.cpp:9588
clang::VarDecl::isFileVarDecl
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition: Decl.h:1301
clang::NestedNameSpecifier::Super
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
Definition: NestedNameSpecifier.h:101
clang::DeclSpec::getRestrictSpecLoc
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:569
clang::DeclContext::decls
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2184
clang::RecordDecl::setArgPassingRestrictions
void setArgPassingRestrictions(ArgPassingKind Kind)
Definition: Decl.h:4155
clang::Decl::setDeclContext
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:336
clang::VarDecl::getTLSKind
TLSKind getTLSKind() const
Definition: Decl.cpp:2096
clang::FPOptions::isFPConstrained
bool isFPConstrained() const
Definition: LangOptions.h:736
clang::InitializationSequence::steps
step_range steps() const
Definition: Initialization.h:1230
clang::DeclSpec::TST_typeof_unqualExpr
static const TST TST_typeof_unqualExpr
Definition: DeclSpec.h:293
clang::interp::APInt
llvm::APInt APInt
Definition: Integral.h:29
clang::UnqualifiedId::TemplateId
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1025
clang::Sema::ForVisibleRedeclaration
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
Definition: Sema.h:4344
clang::RecordDecl::setHasFlexibleArrayMember
void setHasFlexibleArrayMember(bool V)
Definition: Decl.h:4055
clang::DeclContext::specific_decl_iterator
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2204
clang::Sema::TUKind
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Sema.h:1469
clang::MultiVersionKind::CPUDispatch
@ CPUDispatch
clang::Sema::deduceOpenCLAddressSpace
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:6870
clang::TemplateIdAnnotation
Information about a template-id annotation token.
Definition: ParsedTemplate.h:149
clang::TypeSourceInfo::getType
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:6617
clang::ASTContext::UnsignedShortTy
CanQualType UnsignedShortTy
Definition: ASTContext.h:1088
clang::UnqualifiedIdKind::IK_OperatorFunctionId
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
clang::ASTContext::GetGVALinkageForFunction
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
Definition: ASTContext.cpp:11684
clang::Sema::ActOnTypedefNameDecl
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
Definition: SemaDecl.cpp:6724
clang::Sema::AvailabilityMergeKind
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition: Sema.h:3592
clang::EnumConstantDecl::Create
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition: Decl.cpp:5121
clang::AttributeCommonInfo::Kind
Kind
Definition: AttributeCommonInfo.h:55
clang::Sema::CFT_Host
@ CFT_Host
Definition: Sema.h:13051
clang::ASTContext::ResetObjCLayout
void ResetObjCLayout(const ObjCContainerDecl *CD)
Definition: ASTContext.cpp:10899
clang::TargetInfo::isValidGCCRegisterName
virtual bool isValidGCCRegisterName(StringRef Name) const
Returns whether the passed in string is a valid register name according to GCC.
Definition: TargetInfo.cpp:625
clang::Sema::CUDAFunctionTarget
CUDAFunctionTarget
Definition: Sema.h:13048
clang::ObjCIvarDecl::None
@ None
Definition: DeclObjC.h:1944
clang::Sema::CheckRedeclarationExported
bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old)
Definition: SemaDecl.cpp:1695
clang::CXXMethodDecl::isStatic
bool isStatic() const
Definition: DeclCXX.cpp:2142
clang::LabelDecl::isResolvedMSAsmLabel
bool isResolvedMSAsmLabel() const
Definition: Decl.h:531
clang::CXXFinalOverriderMap
A mapping from each virtual member function to its set of final overriders.
Definition: CXXInheritance.h:357
clang::AttributedType
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:4878
clang::QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition: Type.h:6778
clang::VarDecl::setConstexpr
void setConstexpr(bool IC)
Definition: Decl.h:1524
clang::Sema::LookupLocalFriendName
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:4323
clang::Builtin::Context::isConstWithoutErrnoAndExceptions
bool isConstWithoutErrnoAndExceptions(unsigned ID) const
Return true if this function has no side effects and doesn't read memory, except for possibly errno o...
Definition: Builtins.h:247
clang::FunctionDecl::getReturnType
QualType getReturnType() const
Definition: Decl.h:2638
clang::LangOptions::getOpenCLCompatibleVersion
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:63
clang::CXXScopeSpec::Adopt
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
clang::DeclaratorDecl::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:819
clang::ParmVarDecl::getOriginalType
QualType getOriginalType() const
Definition: Decl.cpp:2843
clang::Decl::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:428
isMainFileLoc
static bool isMainFileLoc(const Sema &S, SourceLocation Loc)
Definition: SemaDecl.cpp:1879
copyAttrFromTypedefToDecl
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
Definition: SemaDecl.cpp:7373
clang::FunctionDecl::TK_MemberSpecialization
@ TK_MemberSpecialization
Definition: Decl.h:1931
Error
llvm::Error Error
Definition: ByteCodeEmitter.cpp:21
clang::DeclSpec::TST_enum
static const TST TST_enum
Definition: DeclSpec.h:284
clang::LinkageSpecDecl
Represents a linkage specification.
Definition: DeclCXX.h:2844
clang::TagDecl::setFreeStanding
void setFreeStanding(bool isFreeStanding=true)
True if this tag is free standing, e.g. "struct foo;".
Definition: Decl.h:3579
clang::ASTContext::GE_Missing_setjmp
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2196
clang::SourceRange
A trivial tuple used to represent a source range.
Definition: SourceLocation.h:210
clang::VariableArrayTypeLoc
Definition: TypeLoc.h:1589
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:23
clang::Sema::ActOnDuplicateDefinition
bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
Definition: SemaDecl.cpp:17581
clang::LookupResult::end
iterator end() const
Definition: Lookup.h:336
clang::DeclContext
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1389
getTagInjectionContext
static DeclContext * getTagInjectionContext(DeclContext *DC)
Find the DeclContext in which a tag is implicitly declared if we see an elaborated type specifier in ...
Definition: SemaDecl.cpp:9529
clang::ASTContext::getFunctionFeatureMap
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
Definition: ASTContext.cpp:13416
clang::Sema::mergeAvailabilityAttr
AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority)
Attribute merging methods. Return true if a new attribute was added.
Definition: SemaDeclAttr.cpp:2430
clang::PointerTypeLoc
Wrapper for source info for pointers.
Definition: TypeLoc.h:1258
clang::DefaultInitializedTypeVisitor::visit
RetTy visit(QualType FT, Ts &&... Args)
Definition: NonTrivialTypeVisitor.h:51
clang::FunctionDecl::TK_FunctionTemplate
@ TK_FunctionTemplate
Definition: Decl.h:1928
clang::ASTContext::getDependentNameType
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
Definition: ASTContext.cpp:5175
clang::ObjCSubstitutionContext::Parameter
@ Parameter
The parameter type of a method or function.
clang::Type::isVoidPointerType
bool isVoidPointerType() const
Definition: Type.cpp:593
clang::ASTContext::GetBuiltinType
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
Definition: ASTContext.cpp:11505
clang::CXXConversionDecl
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2778
clang::TST_interface
@ TST_interface
Definition: Specifiers.h:80
clang::Sema::ActOnEnumConstant
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val)
Definition: SemaDecl.cpp:19297
clang::Decl::hasAttr
bool hasAttr() const
Definition: DeclBase.h:560
clang::VarDecl::hasGlobalStorage
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1185
clang::LookupResult::isSingleResult
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:308
SetNestedNameSpecifier
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:6820
clang::Preprocessor::getLastMacroWithSpelling
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens.
Definition: Preprocessor.cpp:357
clang::TypoCorrection
Simple class containing the result of Sema::CorrectTypo.
Definition: TypoCorrection.h:42
clang::ParsedAttributesView::none
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:927
clang::ParenTypeLoc::setLParenLoc
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1157
clang::Sema::AMK_Override
@ AMK_Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition: Sema.h:3600
clang::FixItHint::CreateInsertion
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
clang::ReservedIdentifierStatus::NotReserved
@ NotReserved
clang::RecordDecl::isRandomized
bool isRandomized() const
Definition: Decl.h:4167
clang::Sema::ActOnObjCContainerStartDefinition
void ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl)
Definition: SemaDecl.cpp:17590
clang::DeclaratorChunk::Mem
MemberPointerTypeInfo Mem
Definition: DeclSpec.h:1577
clang::TypoCorrection::getCorrectionSpecifier
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
Definition: TypoCorrection.h:91
clang::TTK_Enum
@ TTK_Enum
The "enum" keyword.
Definition: Type.h:5561
clang::ObjCImplementationDecl
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2584
clang::Sema::getASTContext
ASTContext & getASTContext() const
Definition: Sema.h:1662
clang::DeclSpec::getExplicitSpecLoc
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:604
clang::VarDecl::getCanonicalDecl
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2186
clang::Sema::FnBodyKind
FnBodyKind
Definition: Sema.h:3054
clang::OverloadCandidateSet::CSK_Normal
@ CSK_Normal
Normal lookup.
Definition: Overload.h:955
clang::DecompositionDecl::Create
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition: DeclCXX.cpp:3288
clang::EnumDecl::enumerators
enumerator_range enumerators() const
Definition: Decl.h:3851
clang::NestedNameSpecifier::isDependent
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
Definition: NestedNameSpecifier.cpp:234
clang::Decl::isTemplateParameter
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2611
clang::QualType::isConstQualified
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6707
clang::Decl::getAsFunction
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:227
clang::Declarator::getNumTypeObjects
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2299
clang::Sema::SourceMgr
SourceManager & SourceMgr
Definition: Sema.h:412
clang::FunctionDecl::isConstexpr
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2367
clang::Sema::AddKnownFunctionAttributes
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
Definition: SemaDecl.cpp:16064
getNoteDiagForInvalidRedeclaration
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
Definition: SemaDecl.cpp:3455
clang::DeclSpec::getExplicitSpecRange
SourceRange getExplicitSpecRange() const
Definition: DeclSpec.h:605
Used
@ Used
Definition: ObjCUnusedIVarsChecker.cpp:29
clang::AttributedType::isCallingConv
bool isCallingConv() const
Definition: Type.cpp:3641
Diag
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
Definition: LiteralSupport.cpp:79
clang::Decl::isOutOfLine
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:100
clang::QualifierCollector::apply
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:3846
clang::LookupResult::FoundOverloaded
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
clang::Sema::CheckVariableDeclarationType
void CheckVariableDeclarationType(VarDecl *NewVD)
Definition: SemaDecl.cpp:8453
clang::SourceManager::isInMainFile
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
Definition: SourceManager.cpp:1597
clang::LookupResult::Filter::next
NamedDecl * next()
Definition: Lookup.h:669
getNonCLikeKindForAnonymousStruct
static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD)
Determine whether a class is C-like, according to the rules of C++ [dcl.typedef] for anonymous classe...
Definition: SemaDecl.cpp:4900
clang::Sema::isMicrosoftMissingTypename
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition: SemaDecl.cpp:704
clang::FunctionDecl::isDeleted
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2422
clang::Sema::checkNonTrivialCUnionInInitializer
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
Definition: SemaDecl.cpp:12728
clang::VarDecl::demoteThisDefinitionToDeclaration
void demoteThisDefinitionToDeclaration()
This is a definition which should be demoted to a declaration.
Definition: Decl.h:1438
clang::DeclSpec::isInlineSpecified
bool isInlineSpecified() const
Definition: DeclSpec.h:587
clang::TargetInfo::getLongWidth
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:482
clang::TagDecl::getSourceRange
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4414
clang::DeclSpec::getAttributes
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:818
clang::NamedDecl::isExternallyVisible
bool isExternallyVisible() const
Definition: Decl.h:407
clang::ObjCIvarDecl::Protected
@ Protected
Definition: DeclObjC.h:1944
clang::Qualifiers::OCL_Weak
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:177
SemaInternal.h
clang::ASTContext::setcudaConfigureCallDecl
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1387
clang::TargetInfo::parseTargetAttr
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
Definition: TargetInfo.cpp:534
clang::ConstantArrayType::getSize
const llvm::APInt & getSize() const
Definition: Type.h:3088
clang::BindingDecl
A binding in a decomposition declaration.
Definition: DeclCXX.h:4020
clang::ASTContext::VoidTy
CanQualType VoidTy
Definition: ASTContext.h:1078
clang::DeclarationName::CXXConstructorName
@ CXXConstructorName
Definition: DeclarationName.h:212
clang::DeclSpec::SCS_static
@ SCS_static
Definition: DeclSpec.h:238
clang::sema::LambdaScopeInfo::Mutable
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:853
llvm::SmallVector
Definition: LLVM.h:35
Lookup.h
clang::IdentifierTable::get
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Definition: IdentifierTable.h:597
TryToFixInvalidVariablyModifiedTypeSourceInfo
static TypeSourceInfo * TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
Definition: SemaDecl.cpp:6557
clang::Declarator::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2004
clang::RecordDecl::field_empty
bool field_empty() const
Definition: Decl.h:4231
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::ASTContext::getManglingNumberContext
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
Definition: ASTContext.cpp:12106
emitReadOnlyPlacementAttrWarning
void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD)
Definition: SemaDecl.cpp:7385
clang::Sema::ActOnCXXForRangeDecl
void ActOnCXXForRangeDecl(Decl *D)
Definition: SemaDecl.cpp:13813
clang::QualType::getQualifiers
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6675
clang::ImplicitTypenameContext
ImplicitTypenameContext
Definition: DeclSpec.h:1817
clang::Sema::CodeSegStack
PragmaStack< StringLiteral * > CodeSegStack
Definition: Sema.h:698
clang::TargetCXXABI::isMicrosoft
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:138
clang::ASTContext::getIntWidth
unsigned getIntWidth(QualType T) const
Definition: ASTContext.cpp:10982
clang::Sema::ActOnObjCContainerFinishDefinition
void ActOnObjCContainerFinishDefinition()
Definition: SemaDecl.cpp:17696
clang::VarDecl::isInitCapture
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1530
clang::DiagnosticsEngine::isIgnored
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:911
clang::Module::getFullModuleName
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:239
clang::TTK_Struct
@ TTK_Struct
The "struct" keyword.
Definition: Type.h:5549
clang::Sema::CheckMSVCRTEntryPoint
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
Definition: SemaDecl.cpp:12128
clang::DeclSpec::TST_error
static const TST TST_error
Definition: DeclSpec.h:306
clang::NamedDecl
This represents a decl that may have a name.
Definition: Decl.h:247
clang::DeclContext::getPrimaryContext
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1264
clang::ASTContext::BuiltinInfo
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:633
clang::ParenListExpr
Definition: Expr.h:5384
clang::SourceRange::getBegin
SourceLocation getBegin() const
Definition: SourceLocation.h:219
clang::DeclGroupRef::Create
static DeclGroupRef Create(ASTContext &C, Decl **Decls, unsigned NumDecls)
Definition: DeclGroup.h:68
clang::VarDecl::setInit
void setInit(Expr *I)
Definition: Decl.cpp:2383
DeclHasAttr
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
Definition: SemaDecl.cpp:2733
clang::Attr::getLocation
SourceLocation getLocation() const
Definition: Attr.h:87
clang::TopLevelStmtDecl::Create
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition: Decl.cpp:5266
clang::NamedDecl::isLinkageValid
bool isLinkageValid() const
True if the computed linkage is valid.
Definition: Decl.cpp:1099
clang::UnqualifiedIdKind::IK_DeductionGuideName
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
clang::Sema::ActOnNameClassifiedAsDependentNonType
ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand)
Act on the result of classifying a name as an undeclared member of a dependent base class.
Definition: SemaDecl.cpp:1273
clang::OR_Success
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
EvaluatedExprVisitor.h
clang::FunctionType::ExtInfo::withNoReturn
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:3867
TargetInfo.h
clang::NamedDecl::getUnderlyingDecl
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:459
clang::MultiVersionKind::Target
@ Target
clang::ASTContext::setFILEDecl
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:1908
checkUsingShadowRedecl
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, ExpectedDecl *New)
Check whether a redeclaration of an entity introduced by a using-declaration is valid,...
Definition: SemaDecl.cpp:3513
clang::AttributedTypeLoc::getAttrAs
const T * getAttrAs()
Definition: TypeLoc.h:889
clang::Sema::shouldSkipAnonEnumBody
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
Definition: SemaDecl.cpp:19271
clang::ASTContext::getAdjustedParameterType
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
Definition: ASTContext.cpp:6978
clang::Sema::NonTrivialCUnionContext
NonTrivialCUnionContext
Definition: Sema.h:2991
clang::CastExpr::getSubExpr
Expr * getSubExpr()
Definition: Expr.h:3533
CXXInheritance.h
clang::ParsedTargetAttr
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:54
AreSpecialMemberFunctionsSameKind
static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context, CXXMethodDecl *M1, CXXMethodDecl *M2, Sema::CXXSpecialMember CSM)
[class.mem.special]p5 Two special member functions are of the same kind if:
Definition: SemaDecl.cpp:18421
clang::ASTContext::GE_Missing_ucontext
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2199
clang::DeclSpec::getRepAsExpr
Expr * getRepAsExpr() const
Definition: DeclSpec.h:513
clang::ASTContext::DeclarationNames
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:635
clang::RecordDecl::setHasVolatileMember
void setHasVolatileMember(bool val)
Definition: Decl.h:4083
clang::Stmt::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:325
clang::Sema::CXXDefaultConstructor
@ CXXDefaultConstructor
Definition: Sema.h:1546
clang::CXXRecordDecl::getDefinition
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:548
clang::FunctionDecl::getCanonicalDecl
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3398
clang::MultiExprArg
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:272
clang::VarDecl::TLS_Static
@ TLS_Static
TLS with a known-constant initializer.
Definition: Decl.h:938
clang::DeclSpec::SCS_auto
@ SCS_auto
Definition: DeclSpec.h:239
clang::QualType
A (possibly-)qualified type.
Definition: Type.h:736
clang::TypeDecl::getTypeForDecl
const Type * getTypeForDecl() const
Definition: Decl.h:3270
clang::EnumDecl::isFixed
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:3932
clang::Type::isScalarType
bool isScalarType() const
Definition: Type.h:7291
clang::TemplateName::getAsTemplateDecl
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
Definition: TemplateName.cpp:145
findDefaultInitializer
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
Definition: SemaDecl.cpp:5441
clang::CXXRecordDecl::hasNonTrivialCopyAssignment
bool hasNonTrivialCopyAssignment() const
Determine whether this class has a non-trivial copy assignment operator (C++ [class....
Definition: DeclCXX.h:1303
clang::FunctionDecl::getParamDecl
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2607
clang::FunctionDefinitionKind::Deleted
@ Deleted
clang::Type::isFunctionNoProtoType
bool isFunctionNoProtoType() const
Definition: Type.h:2148
clang::Sema::ActOnTag
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
Definition: SemaDecl.cpp:16615
clang::Redeclarable::redecls_end
redecl_iterator redecls_end() const
Definition: Redeclarable.h:303
clang::Declarator::getIdentifier
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2251
clang::DeclaratorChunk::MemberPointer
@ MemberPointer
Definition: DeclSpec.h:1200
clang::EST_None
@ EST_None
no exception specification
Definition: ExceptionSpecificationType.h:21
clang::TypedefNameDecl::getTypeSourceInfo
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3338
clang::NestedNameSpecifier
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
Definition: NestedNameSpecifier.h:50
clang::Sema::ActOnReenterFunctionContext
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
Definition: SemaDecl.cpp:1470
clang::Sema::PragmaStack
Definition: Sema.h:595
clang::Sema::AddOverriddenMethods
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD)
AddOverriddenMethods - See if a method overrides any in the base classes, and if so,...
Definition: SemaDecl.cpp:8743
clang::tooling::Filter
llvm::cl::opt< std::string > Filter
clang::InitializationSequence::SK_ParenthesizedListInit
@ SK_ParenthesizedListInit
Initialize an aggreagate with parenthesized list of values.
Definition: Initialization.h:930
clang::getDLLAttr
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:54
clang::NamedDecl::hasLinkage
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1872
clang::VarDecl::getInitializingDeclaration
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition: Decl.cpp:2352
clang::ClassScopeFunctionSpecializationDecl
Declaration of a function specialization at template class scope.
Definition: DeclTemplate.h:2627
clang::TST_struct
@ TST_struct
Definition: Specifiers.h:78
clang::FunctionDecl::willHaveBody
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2515
clang::UnresolvedSetIterator
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:32
clang::QualType::getCanonicalType
QualType getCanonicalType() const
Definition: Type.h:6687
clang::FieldDecl
Represents a member of a struct/union/class.
Definition: Decl.h:2943
clang::EnumDecl::getIntegerTypeRange
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition: Decl.cpp:4566
ValidDuplicateEnum
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
Definition: SemaDecl.cpp:19375
clang::sema::FunctionScopeInfo::NeedsScopeChecking
bool NeedsScopeChecking() const
Definition: ScopeInfo.h:472
clang::Sema::FilterLookupForScope
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
Definition: SemaDecl.cpp:1617
clang::TagDecl::setBraceRange
void setBraceRange(SourceRange R)
Definition: Decl.h:3518
clang::Type::isFloatingType
bool isFloatingType() const
Definition: Type.cpp:2145
clang::VarTemplateDecl::getInstantiatedFromMemberTemplate
VarTemplateDecl * getInstantiatedFromMemberTemplate() const
Definition: DeclTemplate.h:3221
clang::DiagnosticsEngine
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
clang::TagDecl::setQualifierInfo
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:4477
clang::DeclaratorChunk::Fun
FunctionTypeInfo Fun
Definition: DeclSpec.h:1575
clang::FunctionType::ExtInfo::getNoCallerSavedRegs
bool getNoCallerSavedRegs() const
Definition: Type.h:3844
clang::LookupResult
Represents the results of name lookup.
Definition: Lookup.h:46
clang::ASTContext::getBaseElementType
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
Definition: ASTContext.cpp:7031
clang::PipeType
PipeType - OpenCL20.
Definition: Type.h:6483
clang::DeclListNode::iterator
Definition: DeclBase.h:1286
clang::TargetInfo::getCXXABI
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1265
clang::ast_matchers::type
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Definition: ASTMatchersInternal.cpp:774
clang::FunctionProtoType::hasExceptionSpec
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:4265
clang::ParmVarDecl
Represents a parameter to a function.
Definition: Decl.h:1724
clang::TypoCorrection::setCorrectionDecl
void setCorrectionDecl(NamedDecl *CDecl)
Clears the list of NamedDecls before adding the new one.
Definition: TypoCorrection.h:166
clang::Sema::Diag
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1877
checkIsValidOpenCLKernelParameter
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
Definition: SemaDecl.cpp:9351
clang::Scope::isCompoundStmtScope
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition: Scope.h:523
clang::Redeclarable::getFirstDecl
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
clang::TargetInfo
Exposes information about the current target.
Definition: TargetInfo.h:205
DeclCXX.h
clang::DeclSpec::hasAutoTypeSpec
bool hasAutoTypeSpec() const
Definition: DeclSpec.h:546
int
__device__ int
Definition: __clang_hip_libdevice_declares.h:63
clang::DeclarationNameTable::getCXXConversionFunctionName
DeclarationName getCXXConversionFunctionName(CanQualType Ty)
Returns the name of a C++ conversion function for the given Type.
Definition: DeclarationName.cpp:337
clang::ASTContext::getFunctionType
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1532
clang::FunctionType::ExtInfo::withProducesResult
ExtInfo withProducesResult(bool producesResult) const
Definition: Type.h:3874
clang::Decl::isUsed
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:457
clang::DeclarationNameInfo::setCXXOperatorNameRange
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
Definition: DeclarationName.h:833
clang::UnqualifiedIdKind::IK_Identifier
@ IK_Identifier
An identifier.
clang::Type::getContainedDeducedType
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:1912
clang::CXXMethodDecl::getCanonicalDecl
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2080
clang::LookupResult::NotFoundInCurrentInstantiation
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
mergeTypeWithPrevious
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
Definition: SemaDecl.cpp:4474
TryToFixInvalidVariablyModifiedType
static QualType TryToFixInvalidVariablyModifiedType(QualType T, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
Definition: SemaDecl.cpp:6441
clang::BinaryConditionalOperator::getCond
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value.
Definition: Expr.h:4257
clang::VarTemplateDecl::getTemplatedDecl
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
Definition: DeclTemplate.h:3164
clang::Sema::DiagnoseSizeOfParametersAndReturnValue
void DiagnoseSizeOfParametersAndReturnValue(ArrayRef< ParmVarDecl * > Parameters, QualType ReturnTy, NamedDecl *D)
Diagnose whether the size of parameters or return value of a function or obj-c method definition is p...
Definition: SemaDecl.cpp:14734
clang::Sema::ActOnCXXForRangeIdentifier
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
Definition: SemaDecl.cpp:13867
clang::EnumConstantDecl::getInitExpr
const Expr * getInitExpr() const
Definition: Decl.h:3177
clang::C99
@ C99
Definition: LangStandard.h:49
clang::UsingShadowDecl
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3234
clang::DeclarationName::CXXDeductionGuideName
@ CXXDeductionGuideName
Definition: DeclarationName.h:216
clang::StringLiteral::getStrTokenLoc
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition: Expr.h:1926
clang::TemplateSpecializationType
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:5361
clang::ASTContext::PSF_Execute
@ PSF_Execute
Definition: ASTContext.h:3310
clang::FunctionDecl::isOverloadedOperator
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2726
clang::SourceRange::isValid
bool isValid() const
Definition: SourceLocation.h:225
clang::ASTContext::PSF_Write
@ PSF_Write
Definition: ASTContext.h:3309
clang::DeclarationNameTable::getCXXDestructorName
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
Definition: DeclarationName.cpp:320
clang::RecoveryExpr
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition: Expr.h:6266
clang::MultiVersionKind::TargetVersion
@ TargetVersion
clang::DeclSpec::isFriendSpecified
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:768
clang::Decl::setTopLevelDeclInObjCContainer
void setTopLevelDeclInObjCContainer(bool V=true)
Definition: DeclBase.h:615
clang::FunctionDecl::getTemplateSpecializationInfo
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:3933
RebuildDeclaratorInCurrentInstantiation
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
RebuildDeclaratorInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in ...
Definition: SemaDecl.cpp:5980
clang::TargetInfo::getCharWidth
unsigned getCharWidth() const
Definition: TargetInfo.h:464
clang::Sema::LookupQualifiedName
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
Definition: SemaLookup.cpp:2418
clang::FunctionType::getExtInfo
ExtInfo getExtInfo() const
Definition: Type.h:3959
clang::Module::isHeaderLikeModule
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition: Module.h:540
clang::DeclSpec::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:525
clang::Sema::FunctionEmissionStatus::Unknown
@ Unknown
clang::Sema::tryToFixVariablyModifiedVarType
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID)
Attempt to fold a variable-sized type to a constant-sized type, returning true if we were successful.
Definition: SemaDecl.cpp:6574
clang::Sema::MergeTypedefNameDecl
void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls)
MergeTypedefNameDecl - We just parsed a typedef 'New' which has the same name and scope as a previous...
Definition: SemaDecl.cpp:2560
clang::FunctionDecl::getPrimaryTemplate
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:3923
clang::FunctionDecl::hasImplicitReturnZero
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition: Decl.h:2325
hasIdenticalPassObjectSizeAttrs
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
Definition: SemaDecl.cpp:3548
clang::TST_enum
@ TST_enum
Definition: Specifiers.h:76
clang::InitListExpr
Describes an C or C++ initializer list.
Definition: Expr.h:4799
clang::QualType::getBaseTypeIdentifier
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition: Type.cpp:73
clang::DeclSpec::SCS
SCS
storage-class-specifier
Definition: DeclSpec.h:234
clang::sema::CapturingScopeInfo::addVLATypeCapture
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition: ScopeInfo.h:710
clang::ParmVarDecl::getObjCDeclQualifier
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1788
clang::DeclSpec::SCS_unspecified
@ SCS_unspecified
Definition: DeclSpec.h:235
clang::Qualifiers::OCL_ExplicitNone
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:167
clang::FunctionDecl::getDeclaredReturnType
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition: Decl.h:2655
clang::TargetInfo::hasFeature
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1382
clang::CXXRecordDecl::Create
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:131
clang::DeclarationNameTable::getCXXDeductionGuideName
DeclarationName getCXXDeductionGuideName(TemplateDecl *TD)
Returns the name of a C++ deduction guide for the given template.
Definition: DeclarationName.cpp:289
clang::ComparisonCategoryType::First
@ First
clang::Sema::ActOnStartCXXMemberDeclarations
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
Definition: SemaDecl.cpp:17596
clang::Declarator::getFunctionDefinitionKind
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition: DeclSpec.h:2650
clang::Decl::getOwningModuleForLinkage
Module * getOwningModuleForLinkage(bool IgnoreLinkage=false) const
Get the module that owns this declaration for linkage purposes.
Definition: Decl.cpp:1572
clang::Module::isModulePartition
bool isModulePartition() const
Is this a module partition.
Definition: Module.h:545
clang::RedeclarableTemplateDecl::setMemberSpecialization
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:913
clang::RecordDecl::getDefinition
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4208
clang::DeclSpec::hasExplicitSpecifier
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:601
clang::ActionResult::isUnset
bool isUnset() const
Definition: Ownership.h:167
clang::TypeLoc::getEndLoc
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:234
clang::Type::isVariableArrayType
bool isVariableArrayType() const
Definition: Type.h:6974
clang::ObjCMethodDecl::param_end
param_const_iterator param_end() const
Definition: DeclObjC.h:360
clang::Sema::notePreviousDefinition
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
Definition: SemaDecl.cpp:4748
clang::Sema::ActOnFields
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:18553
llvm::SmallPtrSet
Definition: ASTContext.h:55
clang::Sema::NonTagKind
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:3286
clang::UnaryOperator
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2175
clang::DeclSpec::TQ_volatile
@ TQ_volatile
Definition: DeclSpec.h:313
clang::TargetInfo::validateCpuSupports
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1399
clang::QualType::getAsString
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1089
clang::TagType
Definition: Type.h:4799
SourceManager.h
getImplicitCodeSegAttrFromClass
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
Definition: SemaDecl.cpp:10733
clang::Decl::getParentFunctionOrMethod
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition: DeclBase.cpp:295
clang::Sema::SkippedDefinitionContext
void * SkippedDefinitionContext
Definition: Sema.h:3472
clang::getLambdaAwareParentOfDeclContext
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:80
clang::ASTConsumer::AssignInheritanceModel
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: ASTConsumer.h:112
clang::SourceManager::getIncludeLoc
SourceLocation getIncludeLoc(FileID FID) const
Returns the include location if FID is a #include'd file otherwise it returns an invalid location.
Definition: SourceManager.h:1145
clang::FunctionDecl::setDefaulted
void setDefaulted(bool D=true)
Definition: Decl.h:2283
clang::TargetInfo::getLongLongWidth
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition: TargetInfo.h:487
clang::Type::isVoidType
bool isVoidType() const
Definition: Type.h:7204
clang::Sema::mergeInternalLinkageAttr
InternalLinkageAttr * mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL)
Definition: SemaDeclAttr.cpp:4811
clang::Decl::isLocalExternDecl
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1134
clang::LangOptions::implicitFunctionsAllowed
bool implicitFunctionsAllowed() const
Returns true if implicit function declarations are allowed in the current language mode.
Definition: LangOptions.h:581
clang::QualType::isVolatileQualified
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6718
clang::DeclarationNameInfo::getCXXOperatorNameRange
SourceRange getCXXOperatorNameRange() const
getCXXOperatorNameRange - Gets the range of the operator name (without the operator keyword).
Definition: DeclarationName.h:825
clang::TagDecl::getTypedefNameForAnonDecl
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3664
clang::Qualifiers::empty
bool empty() const
Definition: Type.h:439
clang::Decl::setIsUsed
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:591
clang::CPlusPlus14
@ CPlusPlus14
Definition: LangStandard.h:55
DeclSpec.h
clang::sema::FunctionScopeInfo::UsesFPIntrin
bool UsesFPIntrin
Whether this function uses constrained floating point intrinsics.
Definition: ScopeInfo.h:139
clang::sema::DelayedDiagnostic::makeForbiddenType
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
Definition: DelayedDiagnostic.h:154
clang::TSCS_thread_local
@ TSCS_thread_local
C++11 thread_local.
Definition: Specifiers.h:229
clang::Decl::getAttr
T * getAttr() const
Definition: DeclBase.h:556
clang::ArrayTypeLoc::getElementLoc
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1549
clang::DeclaratorDecl::getOuterLocStart
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:1978
llvm::Expected
Definition: LLVM.h:37
clang::CXXScopeSpec
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:65
clang::Sema::isSimpleTypeSpecifier
bool isSimpleTypeSpecifier(tok::TokenKind Kind) const
Determine whether the token kind starts a simple-type-specifier.
Definition: SemaDecl.cpp:128
clang::Sema::FunctionEmissionStatus
FunctionEmissionStatus
Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
Definition: Sema.h:4498
clang::ClassTemplatePartialSpecializationDecl
Definition: DeclTemplate.h:2098
clang::VarDecl::setPreviousDeclInSameBlockScope
void setPreviousDeclInSameBlockScope(bool Same)
Definition: Decl.h:1549
clang::OpenCLOptions::isAvailableOption
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
Definition: OpenCLOptions.cpp:32
clang::DeclSpec::TQ_unaligned
@ TQ_unaligned
Definition: DeclSpec.h:314
clang::PrintingPolicy
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
clang::RecordDecl::APK_CanNeverPassInRegs
@ APK_CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
Definition: Decl.h:4022
clang::TypedefNameDecl::setModedTypeSourceInfo
void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy)
Definition: Decl.h:3354
clang::Sema::GetNameFromUnqualifiedId
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5810
clang::Sema::CheckFunctionConstraints
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
Definition: SemaConcept.cpp:606
clang::Sema::ActOnVariableDeclarator
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings=std::nullopt)
Definition: SemaDecl.cpp:7412
clang::sema::Capture
Definition: ScopeInfo.h:536
clang::DeclSpec::TQ_atomic
@ TQ_atomic
Definition: DeclSpec.h:317
clang::VarDecl::setInlineSpecified
void setInlineSpecified()
Definition: Decl.h:1510
ASTLambda.h
clang::FunctionDecl::isInlineSpecified
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2692
clang::diag::Group
Group
Definition: DiagnosticCategories.h:23
clang::ASTContext::getCurrentKeyFunction
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
Definition: RecordLayoutBuilder.cpp:3370
clang::DeclSpec::getConstSpecLoc
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:568
clang::ParsedAttributesView::hasAttribute
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:1007
clang::FunctionDecl::setDeletedAsWritten
void setDeletedAsWritten(bool D=true)
Definition: Decl.h:2430
clang::DeclContext::getLexicalParent
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:1945
InjectAnonymousStructOrUnionMembers
static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, RecordDecl *AnonRecord, AccessSpecifier AS, SmallVectorImpl< NamedDecl * > &Chaining)
InjectAnonymousStructOrUnionMembers - Inject the members of the anonymous struct or union AnonRecord ...
Definition: SemaDecl.cpp:5358
clang::InitializationSequence
Describes the sequence of initializations required to initialize a given object or reference with a s...
Definition: Initialization.h:788
clang::Sema::CheckConversionDeclarator
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
Definition: SemaDeclCXX.cpp:10815
clang::FunctionTemplateDecl::Create
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
Definition: DeclTemplate.cpp:377
clang::ObjCIvarDecl::Public
@ Public
Definition: DeclObjC.h:1944
clang::Sema::mergeAlwaysInlineAttr
AlwaysInlineAttr * mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident)
Definition: SemaDeclAttr.cpp:4796
clang::Sema::IsOverload
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true, bool ConsiderRequiresClauses=true)
Definition: SemaOverload.cpp:1237
clang::FunctionType
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3682
clang::ConstantArrayTypeLoc
Definition: TypeLoc.h:1566
clang::ASTContext::getUsingType
QualType getUsingType(const UsingShadowDecl *Found, QualType Underlying) const
Definition: ASTContext.cpp:4777
clang::Declarator::isDecompositionDeclarator
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition: DeclSpec.h:2247
clang::hlsl::getStageFromEnvironment
constexpr ShaderStage getStageFromEnvironment(const llvm::Triple::EnvironmentType &E)
Definition: HLSLRuntime.h:24
clang::DeclaratorContext::ForInit
@ ForInit
clang::Qualifiers::hasConst
bool hasConst() const
Definition: Type.h:263
isStdBuiltin
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, unsigned BuiltinID)
Determine whether a declaration matches a known function in namespace std.
Definition: SemaDecl.cpp:9549
clang::Token
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
clang::Sema::MarkUnusedFileScopedDecl
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
Definition: SemaDecl.cpp:1948
clang::Sema::PopDeclContext
void PopDeclContext()
Definition: SemaDecl.cpp:1351
clang::TemplateIdAnnotation::NumArgs
unsigned NumArgs
NumArgs - The number of template arguments.
Definition: ParsedTemplate.h:185
clang::TTK_Interface
@ TTK_Interface
The "__interface" keyword.
Definition: Type.h:5552
clang::ImplicitTypenameContext::No
@ No
clang::Sema::DiagnoseClassNameShadow
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
Definition: SemaDecl.cpp:6103
clang::Expr::IgnoreImpCasts
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3016
clang::CXXRecordDecl::lookupInBases
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
Definition: CXXInheritance.cpp:307
clang::DeclSpec::getSpecifierName
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition: DeclSpec.cpp:545
SDK_Field
@ SDK_Field
Definition: SemaDecl.cpp:8086
clang::DeclarationName
The name of a declaration.
Definition: DeclarationName.h:144
End
SourceLocation End
Definition: USRLocFinder.cpp:167
clang::TypoCorrection::getCorrection
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
Definition: TypoCorrection.h:84
clang::ASTContext::getSourceManager
SourceManager & getSourceManager()
Definition: ASTContext.h:692
clang::ASTContext::getDeducedTemplateSpecializationType
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
Definition: ASTContext.cpp:5897
clang::ASTContext::getDecayedType
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
Definition: ASTContext.cpp:3453
clang::CXXRecordDecl::bases_end
base_class_iterator bases_end()
Definition: DeclCXX.h:611
clang::AttributeCommonInfo::AS_GNU
@ AS_GNU
attribute((...))
Definition: AttributeCommonInfo.h:27
clang::Builtin::Context::isPredefinedRuntimeFunction
bool isPredefinedRuntimeFunction(unsigned ID) const
Determines whether this builtin is a predefined compiler-rt/libgcc function, such as "__clear_cache",...
Definition: Builtins.h:174
clang::RecordDecl::isInjectedClassName
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:4728
clang::FieldDecl::isZeroLengthBitField
bool isZeroLengthBitField(const ASTContext &Ctx) const
Is this a zero-length bit-field? Such bit-fields aren't really bit-fields at all and instead act as a...
Definition: Decl.cpp:4312
clang::ASTContext::getTranslationUnitDecl
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1060
clang::VarDecl::setImplicitlyInline
void setImplicitlyInline()
Definition: Decl.h:1515
clang::QualType::PCK_VolatileTrivial
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition: Type.h:1244
clang::sema::LambdaScopeInfo::CallOperator
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:839
clang::Sema::mergeHLSLShaderAttr
HLSLShaderAttr * mergeHLSLShaderAttr(Decl *D, const AttributeCommonInfo &AL, HLSLShaderAttr::ShaderType ShaderType)
Definition: SemaDeclAttr.cpp:7089
clang::LookupResult::begin
iterator begin() const
Definition: Lookup.h:335
clang::FunctionDecl::getLiteralIdentifier
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition: Decl.cpp:3754
clang::LookupResult::getNameLoc
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:632
clang::ArrayType::Normal
@ Normal
Definition: Type.h:3026
clang::Sema::EnterTemplatedContext
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
Definition: SemaDecl.cpp:1427
clang::Decl::isReferenced
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:482
clang::Sema::ActOnPragmaWeakID
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
Definition: SemaDecl.cpp:19832
getCaptureLocation
static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, const VarDecl *VD)
Return the location of the capture if the given lambda captures the given variable VD,...
Definition: SemaDecl.cpp:8109
clang::DeclContextLookupResult::begin
iterator begin()
Definition: DeclBase.h:1348
clang::CXXRecordDecl::hasInClassInitializer
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition: DeclCXX.h:1124
clang::Declarator::getIdentifierLoc
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2257
clang::Declarator::getDeclarationAttributes
const ParsedAttributesView & getDeclarationAttributes() const
Definition: DeclSpec.h:2591
clang::ObjCInterfaceDecl::known_extensions
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1749
clang::FunctionDecl::setFriendConstraintRefersToEnclosingTemplate
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition: Decl.h:2531
clang::EnumDecl::setIntegerType
void setIntegerType(QualType T)
Set the underlying integer type.
Definition: Decl.h:3887
clang::LambdaCaptureInitKind::DirectInit
@ DirectInit
[a(b)]
isIncompleteDeclExternC
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
Definition: SemaDecl.cpp:7183
clang::RecordDecl::setHasNonTrivialToPrimitiveDefaultInitializeCUnion
void setHasNonTrivialToPrimitiveDefaultInitializeCUnion(bool V)
Definition: Decl.h:4124
clang::DeclSpec::getTypeSpecTypeLoc
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:533
clang::DeclaratorChunk::getFunction
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, ArrayRef< NamedDecl * > DeclsInPrototype, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult(), SourceLocation TrailingReturnTypeLoc=SourceLocation(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition: DeclSpec.cpp:161
clang::SourceManager
This class handles loading and caching of source files into memory.
Definition: SourceManager.h:638
clang::DependentNameTypeLoc::setElaboratedKeywordLoc
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2350
clang::CC_X86StdCall
@ CC_X86StdCall
Definition: Specifiers.h:268
clang::Scope::getParent
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:249
clang::FunctionDecl::isConsteval
bool isConsteval() const
Definition: Decl.h:2379
clang::Sema::ActOnDocumentableDecls
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:14527
clang::EnumDecl
Represents an enum.
Definition: Decl.h:3718
clang::FunctionProtoType::isVariadic
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4356
clang::OpaqueValueExpr
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1147
clang::CXXMethodDecl::isMoveAssignmentOperator
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2431
clang::Declarator::getTrailingRequiresClause
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition: DeclSpec.h:2538
clang::Sema::Context
ASTContext & Context
Definition: Sema.h:409
clang::DeclSpec::getExplicitSpecifier
ExplicitSpecifier getExplicitSpecifier() const
Definition: DeclSpec.h:594
clang::Type
The base class of the type hierarchy.
Definition: Type.h:1566
Preprocessor.h
clang::Sema::CheckNontrivialField
bool CheckNontrivialField(FieldDecl *FD)
Definition: SemaDecl.cpp:18123
clang::UsingShadowDecl::getTargetDecl
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3298
clang::FieldDecl::Create
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:4282
clang::Declarator::isStaticMember
bool isStaticMember()
Returns true if this declares a static member.
Definition: DeclSpec.cpp:415
clang::FunctionDecl::isInlined
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2714
clang::FunctionDecl::hasPrototype
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2340
clang::DeclContext::getNonTransparentContext
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1255
clang::FunctionTemplateSpecializationInfo::getTemplate
FunctionTemplateDecl * getTemplate() const
Retrieve the template from which this function was specialized.
Definition: DeclTemplate.h:536
clang::ObjCIvarDecl::AccessControl
AccessControl
Definition: DeclObjC.h:1943
clang::ExprError
ExprResult ExprError()
Definition: Ownership.h:278
computeShadowedDeclKind
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we're shadowing.
Definition: SemaDecl.cpp:8093
canRedefineFunction
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
Definition: SemaDecl.cpp:3476
clang::ConditionalOperator
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4153
clang::Type::isSVESizelessBuiltinType
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2347
clang::CXXScopeSpec::clear
void clear()
Definition: DeclSpec.h:213
clang::TypedefType
Definition: Type.h:4542
clang::Type::containsErrors
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2304
clang::Sema::SFINAETrap
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:9732
clang::UnqualifiedId::StartLocation
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:1031
clang::EnumDecl::isComplete
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:3937
clang::Sema::ActOnTagFinishSkippedDefinition
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
Definition: SemaDecl.cpp:1372
DeclObjC.h
clang::Type::isAggregateType
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2234
clang::CXXMethodDecl::Create
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2230
clang::Type::getAsStructureType
const RecordType * getAsStructureType() const
Definition: Type.cpp:645
clang::ConstexprSpecKind::Constinit
@ Constinit
clang::CXXScopeSpec::isSet
bool isSet() const
Deprecated.
Definition: DeclSpec.h:211
clang::AS_none
@ AS_none
Definition: Specifiers.h:115
clang::LinkageSpecDecl::lang_c
@ lang_c
Definition: DeclCXX.h:2853
getRange
static CharSourceRange getRange(const CharSourceRange &EditRange, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeMacroExpansion)
Definition: SourceCode.cpp:104
clang::FunctionDecl::getDefinition
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition: Decl.h:2186
clang::TypeLoc::getBeginLoc
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:191
clang::CPlusPlus17
@ CPlusPlus17
Definition: LangStandard.h:56
clang::ObjCRuntime::isFragile
bool isFragile() const
The inverse of isNonFragile(): does this runtime follow the set of implied behaviors for a "fragile" ...
Definition: ObjCRuntime.h:97
clang::FixItHint
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
clang::Sema::CheckFieldDecl
FieldDecl * CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D=nullptr)
Build a new FieldDecl and check its well-formedness.
Definition: SemaDecl.cpp:17934
clang::FunctionType::getCmseNSCallAttr
bool getCmseNSCallAttr() const
Definition: Type.h:3957
clang::ASTContext::typesAreCompatible
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
Definition: ASTContext.cpp:10213
clang::InheritableAttr
Definition: Attr.h:136
clang::Sema::CXXMoveConstructor
@ CXXMoveConstructor
Definition: Sema.h:1548
clang::Type::hasAutoForTrailingReturnType
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition: Type.cpp:1917
clang::AttributeCommonInfo::AS_Keyword
@ AS_Keyword
__ptr16, alignas(...), etc.
Definition: AttributeCommonInfo.h:42
clang::Sema::mergeSwiftNameAttr
SwiftNameAttr * mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
Definition: SemaDeclAttr.cpp:4865
clang::Sema::getLangOpts
const LangOptions & getLangOpts() const
Definition: Sema.h:1655
clang::CXXConstructorDecl::Create
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2654
clang::ASTContext::getQualifiedTemplateName
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
Definition: ASTContext.cpp:9257
clang::Sema::MergeCompatibleFunctionDecls
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld)
Completes the merge of two function declarations that are known to be compatible.
Definition: SemaDecl.cpp:4305
clang::BlockDecl::doesNotEscape
bool doesNotEscape() const
Definition: Decl.h:4483
clang::Declarator::takeAttributes
void takeAttributes(ParsedAttributes &attrs)
takeAttributes - Takes attributes from the given parsed-attributes set and add them to this declarato...
Definition: DeclSpec.h:2581
IsPartialSpecialization
Definition: SemaTemplateDeduction.cpp:2835
clang::Expr::getIntegerConstantExpr
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Definition: ExprConstant.cpp:16019
clang::RecordDecl::setHasObjectMember
void setHasObjectMember(bool val)
Definition: Decl.h:4079
clang::DeclSpec::SetRangeStart
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:658
clang::sema::LambdaScopeInfo::Lambda
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:836
clang::FunctionTypeLoc
Wrapper for source info for functions.
Definition: TypeLoc.h:1383
clang::ObjCMethodDecl::param_const_iterator
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:351
clang::Declarator::getDeclSpec
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:1969
clang::CXXRecordDecl::getDescribedClassTemplate
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1853
checkNewAttributesAfterDef
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old)
checkNewAttributesAfterDef - If we already have a definition, check that there are no new attributes ...
Definition: SemaDecl.cpp:3000
clang::Sema::ActOnFinishFunctionBody
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:15371
clang::CanQual::getTypePtr
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
clang::ASTContext::getAssumedTemplateName
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
Definition: ASTContext.cpp:9250
APSInt
llvm::APSInt APSInt
Definition: ByteCodeEmitter.cpp:20
clang::Redeclarable::setPreviousDecl
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4832
U
clang::Sema::LookupTagName
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:4291
clang::ASTContext::isPromotableIntegerType
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
Definition: ASTContext.cpp:1942
synthesizeCurrentNestedNameSpecifier
static NestedNameSpecifier * synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition: SemaDecl.cpp:588
clang::ParmVarDecl::setScopeInfo
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1757
clang::CharSourceRange::getCharRange
static CharSourceRange getCharRange(SourceRange R)
Definition: SourceLocation.h:265
clang::LangAS::opencl_local
@ opencl_local
clang::Sema::CheckForFunctionRedefinition
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
Definition: SemaDecl.cpp:14999
clang::IdentifierInfo::isStr
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Definition: IdentifierTable.h:177
clang::Decl::getLexicalDeclContext
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:883
clang::Sema::LookupMemberName
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:4296
clang::Type::isLiteralType
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2622
clang::Sema::ActOnTagDefinitionError
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
ActOnTagDefinitionError - Invoked when there was an unrecoverable error parsing the definition of a t...
Definition: SemaDecl.cpp:17712
clang::VarDecl::isInline
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1503
clang::VarDecl::isParameterPack
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2582
clang::FunctionTemplateDecl
Declaration of a template function.
Definition: DeclTemplate.h:1005
clang::Sema::mergeImportNameAttr
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
Definition: SemaDeclAttr.cpp:7578
clang::ASTContext::getObjCIdType
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2018
clang::Sema::mergeMinSizeAttr
MinSizeAttr * mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI)
Definition: SemaDeclAttr.cpp:4852
clang::sema::CapturingScopeInfo::addCapture
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:702
llvm::MutableArrayRef
Definition: LLVM.h:32
clang::ASTContext::setNonKeyFunction
void setNonKeyFunction(const CXXMethodDecl *method)
Observe that the given method cannot be a key function.
Definition: RecordLayoutBuilder.cpp:3393
clang::Type::isReferenceType
bool isReferenceType() const
Definition: Type.h:6908
clang::FunctionDecl::setConstexprKind
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2370
clang::CallExpr::getCallee
Expr * getCallee()
Definition: Expr.h:2963
clang::AttributeFactory
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition: ParsedAttr.h:738
clang::IntegerLiteral
Definition: Expr.h:1506
clang::VarDecl::hasInit
bool hasInit() const
Definition: Decl.cpp:2327
clang::QualType::hasNonTrivialObjCLifetime
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1198
diagnoseOpenCLTypes
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
Definition: SemaDecl.cpp:7277
Template.h
clang::prec::Unknown
@ Unknown
Definition: OperatorPrecedence.h:27
clang::ast_matchers::expr
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
Definition: ASTMatchersInternal.cpp:891
BuiltinInfo
static constexpr Builtin::Info BuiltinInfo[]
Definition: Builtins.cpp:32
clang::LangOptions::isCompatibleWithMSVC
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:542
clang::DeclSpec::isNoreturnSpecified
bool isNoreturnSpecified() const
Definition: DeclSpec.h:611
clang::Sema::getShadowedDeclaration
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
Definition: SemaDecl.cpp:8146
clang::Type::isBitIntType
bool isBitIntType() const
Definition: Type.h:7120
clang::ast_matchers::attr
const internal::VariadicAllOfMatcher< Attr > attr
Matches attributes.
Definition: ASTMatchersInternal.cpp:1032
hasDefinition
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Definition: DynamicTypeChecker.cpp:145
clang::InheritableAttr::setInherited
void setInherited(bool I)
Definition: Attr.h:146
clang::Sema::RebuildExprInCurrentInstantiation
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
Definition: SemaTemplate.cpp:11196
clang::Decl::isFunctionOrFunctionTemplate
bool isFunctionOrFunctionTemplate() const
Whether this declaration is a function or function template.
Definition: DeclBase.h:1084
clang::Expr::isTypeDependent
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:187
clang::CXXRecordDecl::getLambdaCaptureDefault
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition: DeclCXX.h:1046
clang::FunctionDecl::getConstexprKind
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2373
clang::VarDecl::setTSCSpec
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition: Decl.h:1132
clang::RecordType
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4823
getHeaderName
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, ASTContext::GetBuiltinTypeError Error)
Definition: SemaDecl.cpp:2359
haveIncompatibleLanguageLinkages
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
Definition: SemaDecl.cpp:3492
clang::DeclSpec::getVolatileSpecLoc
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:570
clang::VarTemplateDecl::Create
static VarTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, VarDecl *Decl)
Create a variable template node.
Definition: DeclTemplate.cpp:1228
clang::Sema::computeNRVO
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope)
Given the set of return statements within a function body, compute the variables that are subject to ...
Definition: SemaDecl.cpp:15308
clang::FunctionDecl::isCPUDispatchMultiVersion
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3366
clang::Module
Describes a module or submodule.
Definition: Module.h:98
clang::Sema::ActOnNameClassifiedAsUndeclaredNonType
ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc)
Act on the result of classifying a name as an undeclared (ADL-only) non-type declaration.
Definition: SemaDecl.cpp:1264
DeclTemplate.h
clang::DeclarationName::getCXXOverloadedOperator
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
Definition: DeclarationName.h:471
clang::Type::isSignedIntegerOrEnumerationType
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2063
clang::Sema::SkipBodyInfo::New
NamedDecl * New
Definition: Sema.h:2589
clang::Sema::SkipBodyInfo::ShouldSkip
bool ShouldSkip
Definition: Sema.h:2586
clang::FunctionDecl::hasSkippedBody
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition: Decl.h:2509
hasSimilarParameters
static bool hasSimilarParameters(ASTContext &Context, FunctionDecl *Declaration, FunctionDecl *Definition, SmallVectorImpl< unsigned > &Params)
hasSimilarParameters - Determine whether the C++ functions Declaration and Definition have "nearly" m...
Definition: SemaDecl.cpp:5945
getOpenCLKernelParameterType
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
Definition: SemaDecl.cpp:9256
clang::OverridingMethods::iterator
MapType::iterator iterator
Definition: CXXInheritance.h:277
clang::Builtin::Context::performsCallback
bool performsCallback(unsigned ID, llvm::SmallVectorImpl< int > &Encoding) const
Determine whether this builtin has callback behavior (see llvm::AbstractCallSites for details).
Definition: Builtins.cpp:209
clang::FTIHasNonVoidParameters
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:36
clang::TargetCXXABI::canKeyFunctionBeInline
bool canKeyFunctionBeInline() const
Can an out-of-line inline function serve as a key function?
Definition: TargetCXXABI.h:240
clang::Sema::ActOnTagFinishDefinition
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
Definition: SemaDecl.cpp:17637
clang::UsingShadowDecl::getIntroducer
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:3043
clang::PartialDiagnosticAt
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
Definition: PartialDiagnostic.h:205
clang::TemplateArgumentListInfo
A convenient class for passing around template argument information.
Definition: TemplateBase.h:590
clang::Linkage
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:23
clang::Declarator::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2005
clang::LangOptions::ObjCRuntime
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:417
clang::DeclSpec::isExternInLinkageSpec
bool isExternInLinkageSpec() const
Definition: DeclSpec.h:463
clang::Decl::getAccess
AccessSpecifier getAccess() const
Definition: DeclBase.h:491
clang::ASTContext::getAsConstantArrayType
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2698
clang::ThreadStorageClassSpecifier
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:223
clang::DeclAccessPair::make
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
Definition: DeclAccessPair.h:35
CheckPoppedLabel
static void CheckPoppedLabel(LabelDecl *L, Sema &S, Sema::DiagReceiverTy DiagReceiver)
Definition: SemaDecl.cpp:2196
clang::Type::getAsTagDecl
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.cpp:1791
GetDiagnosticTypeSpecifierID
static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T)
Definition: SemaDecl.cpp:5030
ExitFunctionBodyRAII
RAII object that pops an ExpressionEvaluationContext when exiting a function body.
Definition: SemaDecl.cpp:15377
clang::Type::isMemberFunctionPointerType
bool isMemberFunctionPointerType() const
Definition: Type.h:6948
clang::ASTContext::getNameForTemplate
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
Definition: ASTContext.cpp:6242
clang::FunctionDecl::isTrivial
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2274
clang::Sema::NameClassification
Definition: Sema.h:2666
clang::TagTypeKind
TagTypeKind
The kind of a tag type.
Definition: Type.h:5547
clang::LangOptions::OMPTargetTriples
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
Definition: LangOptions.h:456
clang::Decl::specific_attrs
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:542
clang::BlockDecl
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4332
clang::Sema::BuildAnonymousStructOrUnion
Decl * BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy)
BuildAnonymousStructOrUnion - Handle the declaration of an anonymous structure or union.
Definition: SemaDecl.cpp:5476
clang::NSAPI::ClassId_NSObject
@ ClassId_NSObject
Definition: NSAPI.h:30
clang::QualType::getAddressSpace
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6769
clang::DeclSpec::getTypeSpecType
TST getTypeSpecType() const
Definition: DeclSpec.h:495
clang::Sema::MergeVarDecl
void MergeVarDecl(VarDecl *New, LookupResult &Previous)
MergeVarDecl - We just parsed a variable 'New' which has the same name and scope as a previous declar...
Definition: SemaDecl.cpp:4511
clang::Sema::ActOnLastBitfield
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
Definition: SemaDecl.cpp:18313
clang::ConstexprSpecKind::Consteval
@ Consteval
clang::Decl::getKind
Kind getKind() const
Definition: DeclBase.h:435
clang::Sema::CXXMoveAssignment
@ CXXMoveAssignment
Definition: Sema.h:1550
clang::ASTContext::getAsIncompleteArrayType
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
Definition: ASTContext.h:2704
clang::C11
@ C11
Definition: LangStandard.h:50
clang::Sema::CheckFunctionDeclaration
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:11605
clang::BinaryOperator
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3815
clang::DeclContext::getEnclosingNamespaceContext
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1847
EquivalentArrayTypes
static bool EquivalentArrayTypes(QualType Old, QualType New, const ASTContext &Ctx)
Definition: SemaDecl.cpp:3360
clang::Decl::setAccess
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:486
clang::FunctionDecl::getTemplatedKind
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3760
clang::Sema::CreateParsedType
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6574
clang::QualType::isObjCGCStrong
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition: Type.h:1189
Id
int Id
Definition: ASTDiff.cpp:190
clang::VarDecl::isStaticLocal
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1167
clang::TagDecl::castFromDeclContext
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition: Decl.h:3710
clang::DeclSpec::UpdateTypeRep
void UpdateTypeRep(ParsedType Rep)
Definition: DeclSpec.h:735
clang::format::encoding::Encoding
Encoding
Definition: Encoding.h:27
clang::Qualifiers::OCL_Strong
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:174
hlsl::uint64_t
unsigned long uint64_t
Definition: hlsl_basic_types.h:25
clang::Type::isNullPtrType
bool isNullPtrType() const
Definition: Type.h:7229
clang::XRayInstrKind::None
constexpr XRayInstrMask None
Definition: XRayInstr.h:38
clang::DeclContext::getDeclKind
Decl::Kind getDeclKind() const
Definition: DeclBase.h:1922
clang::DeclSpec::UpdateExprRep
void UpdateExprRep(Expr *Rep)
Definition: DeclSpec.h:739
clang::Builtin::Context::getHeaderName
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition: Builtins.h:222
clang::Scope
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
clang::Decl::FOK_None
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1176
clang::Sema::EnterDeclaratorContext
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
Definition: SemaDecl.cpp:1379
clang::TemplateIdAnnotation::RAngleLoc
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
Definition: ParsedTemplate.h:182
clang::UnaryOperator::isIncrementDecrementOp
static bool isIncrementDecrementOp(Opcode Op)
Definition: Expr.h:2277
clang::Declarator::getAsmLabel
Expr * getAsmLabel() const
Definition: DeclSpec.h:2615
clang::Scope::isDeclScope
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition: Scope.h:357
clang::Decl::isInStdNamespace
bool isInStdNamespace() const
Definition: DeclBase.cpp:403
clang::CXXScopeSpec::isValid
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:198
clang::syntax::NodeRole::Callee
@ Callee
clang::DeclarationName::CXXDestructorName
@ CXXDestructorName
Definition: DeclarationName.h:213
clang::FunctionType::ExtInfo::getNoReturn
bool getNoReturn() const
Definition: Type.h:3841
clang::DeclaratorDecl::getSourceRange
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2018
clang::Type::isObjCIdType
bool isObjCIdType() const
Definition: Type.h:7057
clang::DeclSpec::TST_interface
static const TST TST_interface
Definition: DeclSpec.h:287
clang::ASTContext::getAsArrayType
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
Definition: ASTContext.cpp:6920
clang::Sema::ActOnObjCReenterContainerContext
void ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx)
Definition: SemaDecl.cpp:17707
clang::Sema::LookupName
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
Definition: SemaLookup.cpp:2179
clang::SourceRange::getEnd
SourceLocation getEnd() const
Definition: SourceLocation.h:220
clang::Declarator::isFirstDeclarationOfMember
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition: DeclSpec.h:2658
clang::Sema::RequireNonAbstractType
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Definition: SemaDeclCXX.cpp:5827
clang::AS_public
@ AS_public
Definition: Specifiers.h:112
clang::Type::isFunctionPointerType
bool isFunctionPointerType() const
Definition: Type.h:6930
clang::threadSafety::sx::toString
std::string toString(const til::SExpr *E)
Definition: ThreadSafetyCommon.h:91
clang::DeclSpec::getUnalignedSpecLoc
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:572
clang::Decl::setAttrs
void setAttrs(const AttrVec &Attrs)
Definition: DeclBase.h:504
clang::ASTContext::PSF_Read
@ PSF_Read
Definition: ASTContext.h:3308
clang::Sema::ActOnField
Decl * ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth)
ActOnField - Each field of a C struct/union is passed into this in order to create a FieldDecl object...
Definition: SemaDecl.cpp:17819
clang::FunctionDecl::getReturnTypeSourceRange
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3640
clang::sema::CapturingScopeInfo::ImpCap_None
@ ImpCap_None
Definition: ScopeInfo.h:675
clang::ParamIdx
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:242
clang::TemplateSpecializationType::anyInstantiationDependentTemplateArguments
static bool anyInstantiationDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args)
Definition: Type.cpp:3768
clang::InitListExpr::children
child_range children()
Definition: Expr.h:4984
clang::ASTContext::DependentTy
CanQualType DependentTy
Definition: ASTContext.h:1106
clang::Sema::PushDeclContext
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1344
clang::VarDecl::isStaticDataMember
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1242
clang::TagDecl::getInnerLocStart
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3522
filterNonConflictingPreviousTypedefDecls
static void filterNonConflictingPreviousTypedefDecls(Sema &S, TypedefNameDecl *Decl, LookupResult &Previous)
Typedef declarations don't have linkage, but they still denote the same entity if their types are the...
Definition: SemaDecl.cpp:2482
clang::FPOptionsOverride
Represents difference between two FPOptions values.
Definition: LangOptions.h:806
clang::FunctionDecl::isThisDeclarationADefinition
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2218
clang::SC_Extern
@ SC_Extern
Definition: Specifiers.h:239
clang::CopiedTypeVisitor
Definition: NonTrivialTypeVisitor.h:78
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
checkForConflictWithNonVisibleExternC
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
Definition: SemaDecl.cpp:8422
clang::MultiTemplateParamsArg
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:276
clang::Sema::ActOnSkippedFunctionBody
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:15361
clang::Sema::FinalizeDeclaration
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:14253
clang::Sema::canFullyTypeCheckRedeclaration
bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT)
Determines if we can perform a correct type check for D as a redeclaration of PrevDecl.
Definition: SemaDecl.cpp:10789
clang::CPlusPlus
@ CPlusPlus
Definition: LangStandard.h:53
clang::Sema::CheckForConstantInitializer
bool CheckForConstantInitializer(Expr *e, QualType t)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12191
clang::Sema::warnOnReservedIdentifier
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6059
clang::ArrayType
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3019
CXXFieldCollector.h
clang::DeclarationNameTable::getCXXOperatorName
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
Definition: DeclarationName.h:648
isOutOfScopePreviousDeclaration
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
Definition: SemaDecl.cpp:6781
clang::Decl::FOK_Undeclared
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1178
clang::AttributedType::getNullabilityAttrKind
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:4931
clang::NamedDecl::getVisibility
Visibility getVisibility() const
Determines the visibility of this entity.
Definition: Decl.h:418
clang::DeclaratorContext::Member
@ Member
clang::Sema::DeduceVariableDeclarationType
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:12694
clang::ParenTypeLoc
Definition: TypeLoc.h:1145
CheckTargetCausesMultiVersioning
static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Definition: SemaDecl.cpp:11152
clang::Qualifiers::removeConst
void removeConst()
Definition: Type.h:265
clang::DependentNameTypeLoc
Definition: TypeLoc.h:2341
recoverFromTypeInKnownDependentBase
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition: SemaDecl.cpp:241
clang::DecompositionDecl
A decomposition declaration.
Definition: DeclCXX.h:4077
clang::DeclaratorChunk::FunctionTypeInfo
Definition: DeclSpec.h:1299
clang::QualType::isNonWeakInMRRWithObjCWeak
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2565
clang::CXXBaseSpecifier::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclCXX.h:190
clang::WeakInfo
Captures information about a #pragma weak directive.
Definition: Weak.h:25
clang::Declarator::getDecompositionDeclarator
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition: DeclSpec.h:1990
clang::ReservedIdentifierStatus
ReservedIdentifierStatus
Definition: IdentifierTable.h:44
clang::FunctionDecl::isCPUSpecificMultiVersion
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3370
clang::DeclSpec::hasConstexprSpecifier
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:782
clang::Sema::CXXCopyConstructor
@ CXXCopyConstructor
Definition: Sema.h:1547
clang::DeclSpec::ClearStorageClassSpecs
void ClearStorageClassSpecs()
Definition: DeclSpec.h:473
clang::Type::getAs
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7410
clang::DiagnosticsEngine::Error
@ Error
Definition: Diagnostic.h:200
clang::TargetInfo::getMaxTLSAlign
unsigned getMaxTLSAlign() const
Return the maximum alignment (in bits) of a TLS variable.
Definition: TargetInfo.h:1464
clang::Sema::SFINAETrap::hasErrorOccurred
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:9763
clang::DeclContext::makeDeclVisibleInContext
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1884
clang::LookupResult::makeFilter
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:708
clang::CXXRecordDecl::getNumBases
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:596
clang::Decl::isInvalidDecl
bool isInvalidDecl() const
Definition: DeclBase.h:571
clang::FunctionDecl::setIneligibleOrNotSelected
void setIneligibleOrNotSelected(bool II)
Definition: Decl.h:2318
clang::ASTContext::getAsVariableArrayType
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2701
clang::CallExpr::getArg
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3004
findRecordWithDependentBasesOfEnclosingMethod
static const CXXRecordDecl * findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC)
Find the parent class with dependent bases of the innermost enclosing method context.
Definition: SemaDecl.cpp:608
clang::Sema::AlignPackInfo
Definition: Sema.h:493
clang::Decl::isInExportDeclContext
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
Definition: DeclBase.cpp:1016
clang::OCD_AmbiguousCandidates
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition: Overload.h:73
clang::Sema::CheckHLSLEntryPoint
void CheckHLSLEntryPoint(FunctionDecl *FD)
Definition: SemaDecl.cpp:12163
clang::Sema::DiagReceiverTy
llvm::function_ref< void(SourceLocation Loc, PartialDiagnostic PD)> DiagReceiverTy
Definition: Sema.h:5284
clang::Module::DefinitionLoc
SourceLocation DefinitionLoc
The location of the module definition.
Definition: Module.h:104
clang::VarDecl::isOutOfLine
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition: Decl.cpp:2367
clang::FunctionType::getCallConv
CallingConv getCallConv() const
Definition: Type.h:3958
clang::DeclarationNameInfo::setName
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
Definition: DeclarationName.h:793
clang::TagDecl::isThisDeclarationADefinition
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition: Decl.h:3536
clang::Sema::AddInitializerToDecl
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13004
clang::Expr::containsErrors
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:240
clang::DeclSpec::TST_class
static const TST TST_class
Definition: DeclSpec.h:288
buildNamedType
static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T, SourceLocation NameLoc, bool WantNontrivialTypeSourceInfo=true)
Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
Definition: SemaDecl.cpp:282
clang::DeclSpec::SCS_typedef
@ SCS_typedef
Definition: DeclSpec.h:236
clang::DeclContext::containsDecl
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1476
clang::ASTContext::getObjCInterfaceType
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
Definition: ASTContext.cpp:5672
clang::Sema::Diags
DiagnosticsEngine & Diags
Definition: Sema.h:411
clang::RecordDecl::setHasNonTrivialToPrimitiveDestructCUnion
void setHasNonTrivialToPrimitiveDestructCUnion(bool V)
Definition: Decl.h:4132
clang::Sema::ClassifyName
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
Definition: SemaDecl.cpp:899
clang::TagDecl::setTypedefNameForAnonDecl
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:4422
clang::Attr::getKind
attr::Kind getKind() const
Definition: Attr.h:80
clang::FunctionProtoType::getParamType
QualType getParamType(unsigned i) const
Definition: Type.h:4236
clang::Declarator::AddTypeInfo
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition: DeclSpec.h:2274
clang::Sema::DiagRuntimeBehavior
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20225
clang::UnqualifiedIdKind::IK_LiteralOperatorId
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
clang::LambdaCaptureDefault
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
Definition: Lambda.h:22
clang::LabelDecl
Represents the declaration of a label.
Definition: Decl.h:496
clang::FunctionDecl::setWillHaveBody
void setWillHaveBody(bool V=true)
Definition: Decl.h:2516
clang::CXXRecordDecl::markAbstract
void markAbstract()
Definition: DeclCXX.h:1837
ModuleLoader.h
DelayedDiagnostic.h
clang::Decl::getCanonicalDecl
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:943
clang::TypoCorrection::isKeyword
bool isKeyword() const
Definition: TypoCorrection.h:202
clang::Token::is
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:98
isFromSystemHeader
static bool isFromSystemHeader(SourceManager &SM, const Decl *D)
Returns true if the declaration is declared in a system header or from a system macro.
Definition: SemaDecl.cpp:6054
clang::sema::FunctionScopeInfo::HasPotentialAvailabilityViolations
bool HasPotentialAvailabilityViolations
Whether we make reference to a declaration that could be unavailable.
Definition: ScopeInfo.h:143
isDeclExternC
static bool isDeclExternC(const Decl *D)
Returns true if given declaration has external C language linkage.
Definition: SemaDecl.cpp:7267
clang::ASTContext::UnknownAnyTy
CanQualType UnknownAnyTy
Definition: ASTContext.h:1106
clang::ConstantArrayType::getMaxSizeBits
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition: Type.cpp:176
clang::Stmt::children
child_range children()
Definition: Stmt.cpp:286
clang::IntegerLiteral::Create
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:983
clang::EnumConstantDecl::getInitVal
const llvm::APSInt & getInitVal() const
Definition: Decl.h:3179
clang::DiagNullabilityKind
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
Definition: Diagnostic.h:1537
clang::BinaryConditionalOperator
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4215
clang::Sema::PDiag
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
clang::ASTContext::getTypeSize
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2274
clang::TypedefNameDecl::getUnderlyingType
QualType getUnderlyingType() const
Definition: Decl.h:3343
clang::ASTContext::getAutoDeductType
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
Definition: ASTContext.cpp:5947
clang::TypoCorrection::getEditDistance
unsigned getEditDistance(bool Normalized=true) const
Gets the "edit distance" of the typo correction from the typo.
Definition: TypoCorrection.h:128
clang::ParenListExpr::getNumExprs
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5410
clang::CXXDestructorDecl
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2715
mergeParamDeclTypes
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
Definition: SemaDecl.cpp:3399
clang::ImplicitCastExpr::Create
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2063
clang::Sema::GetTypeFromParser
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:3107
clang::DeclContext::isTranslationUnit
bool isTranslationUnit() const
Definition: DeclBase.h:2004
clang::AutoType
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5253
clang::DeclRefExpr::getDecl
ValueDecl * getDecl()
Definition: Expr.h:1307
clang::NestedNameSpecifier::containsErrors
bool containsErrors() const
Whether this nested name specifier contains an error.
Definition: NestedNameSpecifier.cpp:246
clang::QualType::hasAddressSpace
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:6764
hasParsedAttr
static bool hasParsedAttr(Scope *S, const Declarator &PD, ParsedAttr::Kind Kind)
Definition: SemaDecl.cpp:7224
clang::DeclSpec::isTypeSpecOwned
bool isTypeSpecOwned() const
Definition: DeclSpec.h:499
clang::Type::isFunctionType
bool isFunctionType() const
Definition: Type.h:6892
clang::UnresolvedLookupExpr::Create
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition: ExprCXX.cpp:370
clang::VariableArrayType::getSizeExpr
Expr * getSizeExpr() const
Definition: Type.h:3188
clang::Declarator::setInvalidType
void setInvalidType(bool Val=true)
Definition: DeclSpec.h:2626
clang::ParsedAttr
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:233
clang::Type::isSizelessType
bool isSizelessType() const
As an extension, we classify types as one of "sized" or "sizeless"; every type is one or the other.
Definition: Type.cpp:2345
clang::UnqualifiedIdKind::IK_ConstructorName
@ IK_ConstructorName
A constructor name.
clang::VarDecl::hasExternalStorage
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1176
clang::Sema::DiagnoseUnusedButSetDecl
void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver)
If VD is set but not otherwise used, diagnose, for a parameter or a variable.
Definition: SemaDecl.cpp:2146
clang::CPlusPlus20
@ CPlusPlus20
Definition: LangStandard.h:57
Expr.h
clang::TargetInfo::validateCpuIs
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:1413
llvm::SmallString
Definition: LLVM.h:34
clang::Expr::EvalResult
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:624
bool
#define bool
Definition: stdbool.h:20
clang::Redeclarable::redecls
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:296
clang::AttrVec
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
Definition: AttrIterator.h:28
clang::LangAS::opencl_constant
@ opencl_constant
clang::TemplateArgumentListInfo::setLAngleLoc
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:609
clang::Sema::GetNameForDeclarator
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5804
ASTContext.h
clang::ASTContext::getRecordType
QualType getRecordType(const RecordDecl *Decl) const
Definition: ASTContext.cpp:4804
clang::LCD_ByCopy
@ LCD_ByCopy
Definition: Lambda.h:24
clang::interp::Zero
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1357
clang::TypeDecl::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3273
clang::CallingConv
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:266
clang::DeclaratorDecl::setTemplateParameterListsInfo
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:1962
clang::Module::isPrivateModule
bool isPrivateModule() const
Definition: Module.h:175
clang::DeclaratorChunk::FunctionTypeInfo::getDeclsInPrototype
ArrayRef< NamedDecl * > getDeclsInPrototype() const
Get the non-parameter decls defined within this function prototype.
Definition: DeclSpec.h:1514
clang::Module::getPrimaryModuleInterfaceName
StringRef getPrimaryModuleInterfaceName() const
Get the primary module interface name from a partition.
Definition: Module.h:562
clang::VarDecl
Represents a variable declaration or definition.
Definition: Decl.h:915
clang::FunctionProtoType::getParamTypes
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4241
clang::Type::isStructureType
bool isStructureType() const
Definition: Type.cpp:567
clang::Sema::ActOnPragmaRedefineExtname
void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaRedefineExtname - Called on well formed #pragma redefine_extname oldname newname.
Definition: SemaDecl.cpp:19805
clang::ASTContext::setObjCClassRedefinitionType
void setObjCClassRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:1839
clang::DeclSpec::TST_typeof_unqualType
static const TST TST_typeof_unqualType
Definition: DeclSpec.h:292
clang::ASTContext::getObjCClassType
QualType getObjCClassType() const
Represents the Objective-C Class type.
Definition: ASTContext.h:2040
clang::Declarator::setFunctionDefinitionKind
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition: DeclSpec.h:2642
clang::Sema::mergeHLSLNumThreadsAttr
HLSLNumThreadsAttr * mergeHLSLNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition: SemaDeclAttr.cpp:6991
clang::Sema::SkipBodyInfo
Definition: Sema.h:2582
shouldConsiderLinkage
static bool shouldConsiderLinkage(const VarDecl *VD)
Definition: SemaDecl.cpp:7197
diagnoseVarDeclTypeMismatch
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
Definition: SemaDecl.cpp:4364
clang::Type::getPointeeType
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:629
clang::TagDecl
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3436
clang::Sema::ImplicitlyDefineFunction
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
Definition: SemaDecl.cpp:15858
clang::ConstexprSpecKind::Constexpr
@ Constexpr
clang::serialization::TypeID
uint32_t TypeID
An ID number that refers to a type in an AST file.
Definition: ASTBitCodes.h:85
clang::FunctionDecl::setHasInheritedPrototype
void setHasInheritedPrototype(bool P=true)
State that this function inherited its prototype from a previous declaration.
Definition: Decl.h:2362
clang::Declarator::hasInitializer
bool hasInitializer() const
Definition: DeclSpec.h:2655
clang::ObjCIvarDecl::Private
@ Private
Definition: DeclObjC.h:1944
clang::TemplateParameterList
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:71
clang::StringLiteral
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1779
clang::TargetInfo::isTLSSupported
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1456
clang::DeclSpec::getStorageClassSpec
SCS getStorageClassSpec() const
Definition: DeclSpec.h:459
clang::TagDecl::setTemplateParameterListsInfo
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4514
clang::OverloadCandidateSet::iterator
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1124
clang::dataflow::var
static constexpr Variable var(Literal L)
Returns the variable of L.
Definition: WatchedLiteralsSolver.cpp:71
clang::TTK_Class
@ TTK_Class
The "class" keyword.
Definition: Type.h:5558
clang::CXXConstructExpr::getConstructor
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1590
clang::Sema::TagUseKind
TagUseKind
Definition: Sema.h:3307
clang::ASTContext::getLifetimeQualifiedType
QualType getLifetimeQualifiedType(QualType type, Qualifiers::ObjCLifetime lifetime)
Return a type with the given lifetime qualifier.
Definition: ASTContext.h:2134
clang::ASTContext::getCanonicalType
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2500
clang::TypeDecl
Represents a declaration of a type.
Definition: Decl.h:3246
clang::DeclaratorDecl::getTrailingRequiresClause
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:843
clang::Type::getAsCXXRecordDecl
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1783
clang::Sema::CheckRedeclarationInModule
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
Definition: SemaDecl.cpp:1734
clang::TTK_Union
@ TTK_Union
The "union" keyword.
Definition: Type.h:5555
clang::tok::ObjCKeywordKind
ObjCKeywordKind
Provides a namespace for Objective-C keywords which start with an '@'.
Definition: TokenKinds.h:41
clang::TagDecl::isUnion
bool isUnion() const
Definition: Decl.h:3642
clang::VarDecl::isLocalVarDecl
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1212
clang::DeclaratorDecl::getQualifier
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:825
RecordKernelParam
@ RecordKernelParam
Definition: SemaDecl.cpp:9231
clang::DeclContext::isNamespace
bool isNamespace() const
Definition: DeclBase.h:2013
clang::Sema::LookupParsedName
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Definition: SemaLookup.cpp:2715
clang::Sema::mergeBTFDeclTagAttr
BTFDeclTagAttr * mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL)
Definition: SemaDeclAttr.cpp:7529
clang::VarDecl::setCXXForRangeDecl
void setCXXForRangeDecl(bool FRD)
Definition: Decl.h:1477
clang::DeclaratorDecl::getTypeSpecStartLoc
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1916
clang::Type::isVariablyModifiedType
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2328
clang::OR_Deleted
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
clang::CXXRecordDecl::bases
base_class_range bases()
Definition: DeclCXX.h:602
clang::CXXDeductionGuideDecl::Create
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor=nullptr)
Definition: DeclCXX.cpp:2114
clang::DeclSpec::getNoreturnSpecLoc
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:612
clang::SC_Register
@ SC_Register
Definition: Specifiers.h:245
clang::CXXRecordDecl::captures
capture_const_range captures() const
Definition: DeclCXX.h:1078
clang::Sema::ParsedFreeStandingDeclSpec
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, const ParsedAttributesView &DeclAttrs, RecordDecl *&AnonRecord)
ParsedFreeStandingDeclSpec - This method is invoked when a declspec with no declarator (e....
Definition: SemaDecl.cpp:4832
clang::FunctionDecl::setPure
void setPure(bool P=true)
Definition: Decl.cpp:3137
mergeAlignedAttrs
static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old)
Merge alignment attributes from Old to New, taking into account the special semantics of C11's _Align...
Definition: SemaDecl.cpp:2764
clang::Sema::getCurFPFeatures
FPOptions & getCurFPFeatures()
Definition: Sema.h:1657
clang::EnumConstantDecl
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3158
clang::FunctionType::ExtInfo::withCallingConv
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:3908
clang::DeclSpec::SetStorageClassSpec
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition: DeclSpec.cpp:626
SDK_Typedef
@ SDK_Typedef
Definition: SemaDecl.cpp:8087
clang::Type::isAtomicType
bool isAtomicType() const
Definition: Type.h:7037
clang::DeclSpec::TST_union
static const TST TST_union
Definition: DeclSpec.h:285
SDK_StaticMember
@ SDK_StaticMember
Definition: SemaDecl.cpp:8085
RebuildLambdaScopeInfo
static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, Sema &S)
Definition: SemaDecl.cpp:15054
clang::Sema::mergeDLLImportAttr
DLLImportAttr * mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI)
Definition: SemaDeclAttr.cpp:7885
SetEligibleMethods
static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record, ArrayRef< CXXMethodDecl * > Methods, Sema::CXXSpecialMember CSM)
[class.mem.special]p6: An eligible special member function is a special member function for which:
Definition: SemaDecl.cpp:18445
clang::ObjCContainerDecl::getIvarDecl
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
getIvarDecl - This method looks up an ivar in this ContextDecl.
Definition: DeclObjC.cpp:80
clang::AttributedTypeLoc
Type source information for an attributed type.
Definition: TypeLoc.h:860
clang::QualifierCollector
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:6575
clang::Sema::mergeFormatAttr
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg)
Definition: SemaDeclAttr.cpp:3897
clang::ParsedType
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition: Ownership.h:243
clang::Decl::setNonMemberOperator
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition: DeclBase.h:1194
clang::ASTContext::getPromotedIntegerType
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
Definition: ASTContext.cpp:7229
clang::NestedNameSpecifierLoc
A C++ nested-name-specifier augmented with source location information.
Definition: NestedNameSpecifier.h:243
clang::Sema::ActOnMSVCUnknownTypeName
ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg)
Attempt to behave like MSVC in situations where lookup of an unqualified type name has failed in a de...
Definition: SemaDecl.cpp:618
clang::Redeclarable::getPreviousDecl
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
clang::LookupResult::getLookupName
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:243
clang::LangOptions::IsHeaderFile
bool IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i....
Definition: LangOptions.h:474
clang::DeclContext::getLookupParent
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1125
clang::OverridingMethods::overriding_iterator
SmallVectorImpl< UniqueVirtualMethod >::iterator overriding_iterator
Definition: CXXInheritance.h:289
clang::DeclSpec::SCS_register
@ SCS_register
Definition: DeclSpec.h:240
clang::Sema::MergeVarDeclTypes
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld)
MergeVarDeclTypes - We parsed a variable 'New' which has the same name and scope as a previous declar...
Definition: SemaDecl.cpp:4387
clang::CanQual< Type >
ExprCXX.h
clang::LookupResult::Filter::erase
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:680
clang::Sema::isTagName
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S)
isTagName() - This method is called for error recovery purposes only to determine if the specified na...
Definition: SemaDecl.cpp:671
Base
Label
std::string Label
Definition: UsingDeclarationsSorter.cpp:96
clang::LCD_None
@ LCD_None
Definition: Lambda.h:23
clang::DeclContext::isRecord
bool isRecord() const
Definition: DeclBase.h:2008
clang::FunctionDecl::getOverloadedOperator
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3746
clang::Redeclarable::isFirstDecl
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition: Redeclarable.h:223
clang::FunctionDecl::Create
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2095
clang::TagDecl::isCompleteDefinition
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3541
clang::DeclSpec::ClearTypeQualifiers
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition: DeclSpec.h:576
clang::Builtin::Context::getName
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
clang::Type::isEnumeralType
bool isEnumeralType() const
Definition: Type.h:6990
clang::DeclaratorChunk::FunctionTypeInfo::Params
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1363
clang::Sema::mergeDLLExportAttr
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
Definition: SemaDeclAttr.cpp:7898
clang::operator<<
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ASTContext::SectionInfo &Section)
Insertion operator for diagnostics.
Definition: ASTContext.cpp:13500
clang::Decl::setImplicit
void setImplicit(bool I=true)
Definition: DeclBase.h:577
clang::Builtin::Context::isConstWithoutExceptions
bool isConstWithoutExceptions(unsigned ID) const
Definition: Builtins.h:251
clang::Sema::isVisible
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:2363
clang::Token::isNot
bool isNot(tok::TokenKind K) const
Definition: Token.h:99
clang::Sema::ActOnIvar
Decl * ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, tok::ObjCKeywordKind visibility)
ActOnIvar - Each ivar field of an objective-c class is passed into this in order to create an IvarDec...
Definition: SemaDecl.cpp:18198
clang::QualType::hasQualifiers
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:6723
clang::DeclSpec::ClearConstexprSpec
void ClearConstexprSpec()
Definition: DeclSpec.h:786
clang::LookupResult::Ambiguous
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
clang::sema::CapturingScopeInfo::ImpCaptureStyle
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:679
clang::Type::getAsAdjusted
const T * getAsAdjusted() const
Member-template getAsAdjusted<specific type>.
Definition: Type.h:7427
clang::sema::FunctionScopeInfo::ObjCShouldCallSuper
bool ObjCShouldCallSuper
A flag that is set when parsing a method that must call super's implementation, such as -dealloc,...
Definition: ScopeInfo.h:148
clang::Sema::MergeFunctionDecl
bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld, bool NewDeclIsDefn)
MergeFunctionDecl - We just parsed a function 'New' from declarator D which has the same name and sco...
Definition: SemaDecl.cpp:3617
clang::Sema::IsValueInFlagEnum
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const
IsValueInFlagEnum - Determine if a value is allowed as part of a flag enum.
Definition: SemaDecl.cpp:19521
clang::Sema::DiagnoseFunctionSpecifiers
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6620
clang::Type::getPointeeOrArrayElementType
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:7367
clang::NamedDecl::hasLinkageBeenComputed
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition: Decl.h:453
clang::Sema::ActOnExitFunctionContext
void ActOnExitFunctionContext()
Definition: SemaDecl.cpp:1494
clang::NestedNameSpecifierLocBuilder
Class that aids in the construction of nested-name-specifiers along with source-location information ...
Definition: NestedNameSpecifier.h:356
clang::DeclSpec::getThreadStorageClassSpecLoc
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:469
clang::ASTContext::setObjCSelRedefinitionType
void setObjCSelRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:1852
clang::DeclSpec::SCS_mutable
@ SCS_mutable
Definition: DeclSpec.h:242
clang::VarDecl::setDescribedVarTemplate
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition: Decl.cpp:2711
clang::MultiVersionKind::TargetClones
@ TargetClones
clang::hasAttribute
int hasAttribute(AttributeCommonInfo::Syntax Syntax, const IdentifierInfo *Scope, const IdentifierInfo *Attr, const TargetInfo &Target, const LangOptions &LangOpts)
Return the version number associated with the attribute if we recognize and implement the attribute s...
Definition: Attributes.cpp:7
clang::Sema::DelayedDiagnostics::shouldDelayDiagnostics
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition: Sema.h:960
clang::ObjCMessageExpr
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:940
clang::QualType::hasNonTrivialToPrimitiveDestructCUnion
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition: Type.h:6784
isTemplate
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
Definition: ItaniumMangle.cpp:931
isFunctionDefinitionDiscarded
static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD)
Given that we are within the definition of the given function, will that definition behave like C99's...
Definition: SemaDecl.cpp:7152
clang::Declarator::isFunctionDeclarator
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2361
clang::QualType::getSingleStepDesugaredType
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:1066
clang::RecordDecl::isAnonymousStructOrUnion
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4070
clang::Type::getTypeClass
TypeClass getTypeClass() const
Definition: Type.h:1985
clang::Sema::getOpenCLOptions
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:1656
clang::VarDecl::Create
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2079
clang::AdjustedType
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:2805
clang::SourceManager::getDecomposedLoc
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
Definition: SourceManager.h:1246
clang::TemplateParameterList::getTemplateLoc
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:193
clang::CXXScopeSpec::getWithLocInContext
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:152
clang::TypeLocBuilder
Definition: TypeLocBuilder.h:22
clang::CastExpr::getCastKind
CastKind getCastKind() const
Definition: Expr.h:3527
clang::Decl::isImplicit
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:576
clang::Qualifiers::OCL_Autoreleasing
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:180
clang::DeclaratorChunk::ParamInfo::Param
Decl * Param
Definition: DeclSpec.h:1277
clang::MemberExpr::getMemberDecl
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3255
clang::Decl::getOwningModule
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:808
clang::ASTContext::ShortTy
CanQualType ShortTy
Definition: ASTContext.h:1087
clang::Sema::AMK_OptionalProtocolImplementation
@ AMK_OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition: Sema.h:3606
clang::NamedDecl::getFormalLinkage
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.h:398
clang::Sema::PopExpressionEvaluationContext
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:17969
clang::OverloadCandidateSet::NoteCandidates
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
Definition: SemaOverload.cpp:11973
clang::Sema::mergeUuidAttr
UuidAttr * mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl)
Definition: SemaDeclAttr.cpp:6856
clang::FunctionDefinitionKind::Declaration
@ Declaration
clang::Decl::dropAttr
void dropAttr()
Definition: DeclBase.h:531
clang::IncompleteArrayType
Represents a C array with an unspecified size.
Definition: Type.h:3125
clang::ASTContext::getFunctionNoProtoType
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
Definition: ASTContext.cpp:4383
clang::DecompositionDeclarator::getSourceRange
SourceRange getSourceRange() const
Definition: DeclSpec.h:1770
clang::CXXDestructorDecl::Create
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2788
clang::Qualifiers::ObjCLifetime
ObjCLifetime
Definition: Type.h:161
clang::RecordDecl::setAnonymousStructOrUnion
void setAnonymousStructOrUnion(bool Anon)
Definition: Decl.h:4074
clang::Sema::LookupNameKind
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:4284
clang::Sema::CheckThreadLocalForLargeAlignment
void CheckThreadLocalForLargeAlignment(VarDecl *VD)
Definition: SemaDecl.cpp:14231
clang::ConstraintSatisfaction::IsSatisfied
bool IsSatisfied
Definition: ASTConcept.h:46
clang::Builtin::evaluateRequiredTargetFeatures
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
clang::DeclRefExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:599
clang::ASTContext::setManglingNumber
void setManglingNumber(const NamedDecl *ND, unsigned Number)
Definition: ASTContext.cpp:12075
clang::Decl::IDNS_Ordinary
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:141
clang::SC_Static
@ SC_Static
Definition: Specifiers.h:240
clang::Declarator::SetIdentifier
void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2260
clang::Sema::LangOpts
const LangOptions & LangOpts
Definition: Sema.h:407
TranslateIvarVisibility
static ObjCIvarDecl::AccessControl TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility)
TranslateIvarVisibility - Translate visibility from a token ID to an AST enum value.
Definition: SemaDecl.cpp:18186
clang::AttributedTypeLoc::getModifiedLoc
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition: TypeLoc.h:877
clang::sema::CapturingScopeInfo::ImpCap_LambdaByval
@ ImpCap_LambdaByval
Definition: ScopeInfo.h:675
clang::TemplateDecl::getTemplateParameters
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:426
clang::APIntStorage::getValue
llvm::APInt getValue() const
Definition: Expr.h:1490
clang::Sema::ActOnUninitializedDecl
void ActOnUninitializedDecl(Decl *dcl)
Definition: SemaDecl.cpp:13528
clang::Sema::ActOnInitializerError
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
Definition: SemaDecl.cpp:13486
clang::ASTContext::UnsignedLongLongTy
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1089
clang::ETK_None
@ ETK_None
No keyword precedes the qualified type name.
Definition: Type.h:5587
clang::Sema::ConvertDeclToDeclGroup
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:59
clang::QualType::getUnqualifiedType
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6728
clang::Type::isObjCLifetimeType
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4441
clang::FunctionDecl::setHasImplicitReturnZero
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition: Decl.h:2332
clang::Module::Parent
Module * Parent
The parent of this module.
Definition: Module.h:135
CharUnits.h
clang::DeclarationNameInfo::getName
DeclarationName getName() const
getName - Returns the embedded declaration name.
Definition: DeclarationName.h:790
clang::FunctionDecl::isReplaceableGlobalAllocationFunction
bool isReplaceableGlobalAllocationFunction(std::optional< unsigned > *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:3210
clang::ASTContext::hasSameFunctionTypeIgnoringPtrSizes
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
Definition: ASTContext.cpp:3322
clang::CC_C
@ CC_C
Definition: Specifiers.h:267
clang::QualType::PCK_Trivial
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition: Type.h:1239
clang::Sema::PushLambdaScope
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:2134
clang::Type::isObjCObjectPointerType
bool isObjCObjectPointerType() const
Definition: Type.h:7024
clang::LookupResult::Filter::hasNext
bool hasNext() const
Definition: Lookup.h:665
clang::FunctionType::ExtInfo::withRegParm
ExtInfo withRegParm(unsigned RegParm) const
Definition: Type.h:3902
clang::CXXRecordDecl::addedSelectedDestructor
void addedSelectedDestructor(CXXDestructorDecl *DD)
Notify the class that this destructor is now selected.
Definition: DeclCXX.cpp:1374
clang::ObjCCategoryDecl
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2312
clang::FunctionDecl::hasBody
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3038
clang::Sema::CorrectTypo
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
Definition: SemaLookup.cpp:5375
clang::Sema::getElaboratedType
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl=nullptr)
Retrieve a version of the type 'T' that is elaborated by Keyword, qualified by the nested-name-specif...
Definition: SemaType.cpp:9204
clang::Visibility
Visibility
Describes the different kinds of visibility that a declaration may have.
Definition: Visibility.h:33
clang::TemplateParameterList::getRAngleLoc
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:195
clang::Type::isFunctionProtoType
bool isFunctionProtoType() const
Definition: Type.h:2149
clang::Sema::SkipBodyInfo::CheckSameAsPrevious
bool CheckSameAsPrevious
Definition: Sema.h:2587
clang::InitializationKind::CreateDefault
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
Definition: Initialization.h:682
ShadowedDeclKind
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
Definition: SemaDecl.cpp:8082
clang::ParsedAttributesView::empty
bool empty() const
Definition: ParsedAttr.h:932
isTagTypeWithMissingTag
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition: SemaDecl.cpp:850
clang::Sema::CheckDeductionGuideDeclarator
void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
Definition: SemaDeclCXX.cpp:11058
clang::VarDecl::getDescribedVarTemplate
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2706
clang::DeducedType::isDeduced
bool isDeduced() const
Definition: Type.h:5241
clang::ASTContext::UnsignedCharTy
CanQualType UnsignedCharTy
Definition: ASTContext.h:1088
clang::Sema::ActOnFinishKNRParamDeclarations
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Definition: SemaDecl.cpp:14849
clang::OpaquePtr
Wrapper for void* pointer.
Definition: Ownership.h:50
clang::Declarator::setRedeclaration
void setRedeclaration(bool Val)
Definition: DeclSpec.h:2671
clang::DeducedType::getDeducedType
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it has not been deduced.
Definition: Type.h:5240
RemoveUsingDecls
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations from the lookup results.
Definition: SemaDecl.cpp:1825
clang::DeclarationName::CXXConversionFunctionName
@ CXXConversionFunctionName
Definition: DeclarationName.h:214
clang::DeclSpec::TST_int
static const TST TST_int
Definition: DeclSpec.h:268
clang::Sema::mergeCodeSegAttr
CodeSegAttr * mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
Definition: SemaDeclAttr.cpp:3355
clang::FunctionProtoType::ExtProtoInfo::withExceptionSpec
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition: Type.h:4121
CheckAnonMemberRedeclaration
static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S, DeclContext *Owner, DeclarationName Name, SourceLocation NameLoc, bool IsUnion)
We are trying to inject an anonymous member into the given scope; check if there's an existing declar...
Definition: SemaDecl.cpp:5317
clang::TemplateIdAnnotation::LAngleLoc
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
Definition: ParsedTemplate.h:178
clang::OverloadCandidateSet
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:951
clang::LangAS
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
clang::VarDecl::isThisDeclarationADemotedDefinition
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition: Decl.h:1428
clang::DeclSpec::getStorageClassSpecLoc
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:468
clang::FunctionDecl::isGlobal
bool isGlobal() const
Determines whether this is a global function.
Definition: Decl.cpp:3321
clang::supportsVariadicCall
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition: Specifiers.h:292
clang::Sema::isAcceptableTagRedeclaration
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
Definition: SemaDecl.cpp:16421
clang::sema::FunctionScopeInfo
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:102
clang::Sema::AbstractReturnType
@ AbstractReturnType
Definition: Sema.h:7937
clang::isDiscardableGVALinkage
bool isDiscardableGVALinkage(GVALinkage L)
Definition: Linkage.h:76
clang::ParsedAttributesView::Range
SourceRange Range
Definition: ParsedAttr.h:925
clang::Sema::DiagnoseShadowingLambdaDecls
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
Definition: SemaDecl.cpp:8282
clang::Sema::HandleField
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
HandleField - Analyze a field of a C struct or a C++ data member.
Definition: SemaDecl.cpp:17829
ShouldWarnAboutMissingPrototype
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:14946
clang::OCD_AllCandidates
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition: Overload.h:67
clang::Sema::diagnoseTypo
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
Definition: SemaLookup.cpp:5672
clang::Type::castAs
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7477
clang::Sema::canDelayFunctionBody
bool canDelayFunctionBody(const Declarator &D)
Determine whether we can delay parsing the body of a function or function template until it is used,...
Definition: SemaDecl.cpp:15319
clang::Sema::FinalizeDeclaratorGroup
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:14412
clang::diff::Delete
@ Delete
Definition: ASTDiff.h:30
clang::Sema::TemplateNameKindForDiagnostics
TemplateNameKindForDiagnostics
Describes the detailed kind of a template name. Used in diagnostics.
Definition: Sema.h:2827
clang::OverloadCandidateSet::BestViableFunction
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
Definition: SemaOverload.cpp:10249
clang::ConstexprSpecKind
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition: Specifiers.h:32
clang::Sema::mergeVisibilityAttr
VisibilityAttr * mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis)
Definition: SemaDeclAttr.cpp:2867
clang::QualType::getDesugaredType
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:1053
clang::Sema::ActOnObjCTemporaryExitContainerContext
void ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx)
Invoked when we must temporarily exit the objective-c container scope for parsing/looking-up C constr...
Definition: SemaDecl.cpp:17701
clang::CXXRecordDecl::addedEligibleSpecialMemberFunction
void addedEligibleSpecialMemberFunction(const CXXMethodDecl *MD, unsigned SMKind)
Notify the class that an eligible SMF has been added.
Definition: DeclCXX.cpp:1379
clang::TargetInfo::getTriple
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1190
clang::AccessSpecifier
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:111
clang::ASTContext::UnsignedLongTy
CanQualType UnsignedLongTy
Definition: ASTContext.h:1088
clang::Sema::shouldLinkDependentDeclWithPrevious
bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl)
Checks if the new declaration declared in dependent context must be put in the same redeclaration cha...
Definition: SemaDecl.cpp:10822
clang::DependentNameTypeLoc::setQualifierLoc
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2359
clang::Decl::isInIdentifierNamespace
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:858
clang::VarDecl::ListInit
@ ListInit
Direct list-initialization (C++11)
Definition: Decl.h:926
clang::MemberExpr::getBase
Expr * getBase() const
Definition: Expr.h:3249
clang::Sema::LazilyCreateBuiltin
NamedDecl * LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc)
LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
Definition: SemaDecl.cpp:2417
clang::InitializationSequence::Perform
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Definition: SemaInit.cpp:8292
clang::Sema::MarkTypoCorrectedFunctionDefinition
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
Definition: SemaDecl.cpp:8850
StorageClassSpecToVarDeclStorageClass
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
Definition: SemaDecl.cpp:5420
clang::ArrayTypeLoc::getRBracketLoc
SourceLocation getRBracketLoc() const
Definition: TypeLoc.h:1529
clang::TemplateArgumentListInfo::arguments
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:618
clang::isWhitespace
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition: CharInfo.h:93
clang::DecompositionDeclarator::getLSquareLoc
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1768
clang::CXXRecordDecl
Represents a C++ struct/union/class.
Definition: DeclCXX.h:254
clang::CXXMethodDecl::getMethodQualifiers
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2140
clang::ArrayTypeLoc::getSizeExpr
Expr * getSizeExpr() const
Definition: TypeLoc.h:1541
clang::FunctionDecl::getNameInfo
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2117
clang::ObjCMethodDecl::param_iterator
ParmVarDecl *const * param_iterator
Definition: DeclObjC.h:352
clang::Type::isImageType
bool isImageType() const
Definition: Type.h:7109
CreateNewFunctionDecl
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
Definition: SemaDecl.cpp:9050
clang::FunctionDecl::setPreviousDeclaration
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition: Decl.cpp:3384
clang::sema::AnalysisBasedWarnings::Policy
Definition: AnalysisBasedWarnings.h:33
clang::FunctionType::ExtInfo::getHasRegParm
bool getHasRegParm() const
Definition: Type.h:3846
clang::UnqualifiedIdKind::IK_TemplateId
@ IK_TemplateId
A template-id, e.g., f<int>.
clang::VarDecl::isThisDeclarationADefinition
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2189
clang::Sema::getNonTagTypeDeclKind
NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK)
Given a non-tag type declaration, returns an enum useful for indicating what kind of non-tag type thi...
Definition: SemaDecl.cpp:16392
clang::Type::getAsUnionType
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:664
clang::LabelDecl::getStmt
LabelStmt * getStmt() const
Definition: Decl.h:520
clang::tok::TokenKind
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
clang::Type::isUnionType
bool isUnionType() const
Definition: Type.cpp:599
clang::DeclContext::getRedeclContext
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1829
clang::ASTContext::adjustFunctionType
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
Definition: ASTContext.cpp:3231
HLSLRuntime.h
clang::ASTContext::LongLongTy
CanQualType LongLongTy
Definition: ASTContext.h:1087
clang::ast_matchers::decl
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
Definition: ASTMatchersInternal.cpp:735
clang::Declarator::getCXXScopeSpec
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:1984
P
StringRef P
Definition: ASTMatchersInternal.cpp:564
clang::Sema::CTK_ErrorRecovery
@ CTK_ErrorRecovery
Definition: Sema.h:4526
isUsingDecl
static bool isUsingDecl(NamedDecl *D)
Definition: SemaDecl.cpp:1818
clang::Attr::isInherited
bool isInherited() const
Definition: Attr.h:89
clang::Sema::TemplateDeductionResult
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:8953
clang::Type::isDependentType
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2310
clang::Type::isInstantiationDependentType
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2318
clang::TargetInfo::getTargetOpts
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition: TargetInfo.h:280
clang::VK_PRValue
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:123
clang::TypedefNameDecl::getAnonDeclWithTypedefName
TagDecl * getAnonDeclWithTypedefName(bool AnyRedecl=false) const
Retrieves the tag declaration for which this is the typedef name for linkage purposes,...
Definition: Decl.cpp:5179
clang::FunctionType::getNameForCallConv
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:3179
clang::Sema::IsRedefinitionInModule
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Definition: SemaDecl.cpp:1760
clang::sema::FunctionScopeInfo::ObjCWarnForNoInitDelegation
bool ObjCWarnForNoInitDelegation
This starts true for a secondary initializer method and will be set to false if there is an invocatio...
Definition: ScopeInfo.h:165
clang::QualType::isCanonical
bool isCanonical() const
Definition: Type.h:6692
clang::Attr::clone
Attr * clone(ASTContext &C) const
clang::AttributeCommonInfo::getRange
SourceRange getRange() const
Definition: AttributeCommonInfo.h:133
clang::LCD_ByRef
@ LCD_ByRef
Definition: Lambda.h:25
clang::TypeWithKeyword::getTagTypeKindForTypeSpec
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:2856
clang::LookupResult::suppressDiagnostics
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:609
clang::ASTContext::UnsignedIntTy
CanQualType UnsignedIntTy
Definition: ASTContext.h:1088
clang::Type::getContainedAutoType
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2415
clang::TagDecl::startDefinition
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4431
clang::attr::Kind
Kind
Definition: AttrKinds.h:22
clang::Decl::getPreviousDecl
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1026
clang::VariableArrayType
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3169
clang::FunctionTemplateSpecializationInfo
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:477
clang::Decl::getFriendObjectKind
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1185
clang::sema::CapturingScopeInfo::Captures
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:692
clang::LookupResult::empty
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:339
clang::FieldDecl::isBitField
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3021
clang::Type::canDecayToPointerType
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:7347
clang::Type::isPointerType
bool isPointerType() const
Definition: Type.h:6896
clang::EnumDecl::isScoped
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:3923
clang::Sema::getScopeForDeclContext
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
Definition: SemaDecl.cpp:1600
clang::Decl::hasAttrs
bool hasAttrs() const
Definition: DeclBase.h:502
clang::Declarator::getFunctionTypeInfo
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2392
clang::FunctionType::ExtInfo::withNoCallerSavedRegs
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition: Type.h:3888
clang::Module::isGlobalModule
bool isGlobalModule() const
Does this Module scope describe a fragment of the global module within some C++ module.
Definition: Module.h:173
clang::Scope::TemplateParamScope
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:78
clang::LookupResult::AmbiguousTagHiding
@ AmbiguousTagHiding
Name lookup results in an ambiguity because an entity with a tag name was hidden by an entity with an...
Definition: Lookup.h:135
CheckConvertedConstantExpression
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, Sema::CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
Definition: SemaOverload.cpp:5780
clang::Builtin::Context::isConst
bool isConst(unsigned ID) const
Return true if this function has no side effects and doesn't read memory.
Definition: Builtins.h:122
isRepresentableIntegerValue
static bool isRepresentableIntegerValue(ASTContext &Context, llvm::APSInt &Value, QualType T)
Determine whether the given integral value is representable within the given type T.
Definition: SemaDecl.cpp:19050
clang::TypeLoc::getAsAdjusted
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2631
isOpenCLSizeDependentType
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty)
Definition: SemaDecl.cpp:9234
clang::NamedDecl::hasExternalFormalLinkage
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition: Decl.h:403
clang::TypedefType::getDecl
TypedefNameDecl * getDecl() const
Definition: Type.h:4553
getRedeclDiagFromTagKind
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
Definition: SemaDecl.cpp:16374
clang::DeclSpec::isDeclRep
static bool isDeclRep(TST T)
Definition: DeclSpec.h:427
clang::TypedefNameDecl::setTypeSourceInfo
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3350
clang::OR_No_Viable_Function
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
clang::InitializationSequence::step_begin
step_iterator step_begin() const
Definition: Initialization.h:1225
clang::TagDecl::isBeingDefined
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3561
clang::CXXRecordDecl::hasNonTrivialCopyConstructor
bool hasNonTrivialCopyConstructor() const
Determine whether this class has a non-trivial copy constructor (C++ [class.copy]p6,...
Definition: DeclCXX.h:1257
clang::ASTContext::getDeclAlign
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
Definition: ASTContext.cpp:1783
clang::ASTContext::getAttributedType
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
Definition: ASTContext.cpp:4846
clang::TypeLoc::getUnqualifiedLoc
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition: TypeLoc.h:326
clang::FunctionType::ExtInfo::getCC
CallingConv getCC() const
Definition: Type.h:3855
clang::ActionResult::get
PtrTy get() const
Definition: Ownership.h:169
clang::OverloadCandidateDisplayKind
OverloadCandidateDisplayKind
Definition: Overload.h:64
clang::LCK_ByRef
@ LCK_ByRef
Capturing by reference.
Definition: Lambda.h:37
clang::NamedDecl::getIdentifier
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:268
clang::ClassTemplateDecl
Declaration of a class template.
Definition: DeclTemplate.h:2270
clang::ValueDecl
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:703
clang::FunctionDecl::setTrivial
void setTrivial(bool IT)
Definition: Decl.h:2275
clang::TNK_Type_template
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
clang::AS_protected
@ AS_protected
Definition: Specifiers.h:113
clang::ASTContext::IntTy
CanQualType IntTy
Definition: ASTContext.h:1087
clang::RecordDecl::completeDefinition
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:4774
clang::ASTContext::addModuleInitializer
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
Definition: ASTContext.cpp:1205
clang::ASTContext::GE_Missing_stdio
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2193
mergeParamDeclAttributes
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one.
Definition: SemaDecl.cpp:3317
GenerateFixForUnusedDecl
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
Definition: SemaDecl.cpp:2083
clang::DeclSpec::isModulePrivateSpecified
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:774
clang::ASTContext::PSF_Implicit
@ PSF_Implicit
Definition: ASTContext.h:3311
clang::LangOptions::NonGC
@ NonGC
Definition: LangOptions.h:87
clang::FunctionDecl::getLanguageLinkage
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition: Decl.cpp:3303
clang::TypedefType::desugar
QualType desugar() const
Definition: Type.cpp:3451
clang::CXXLanguageLinkage
@ CXXLanguageLinkage
Definition: Linkage.h:61
clang::TemplateName
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
clang::VarDecl::getStorageClass
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1127
clang::BinaryOperator::getLHS
Expr * getLHS() const
Definition: Expr.h:3864
clang::Sema::RedeclarationKind
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
Definition: Sema.h:4338
clang::FunctionDecl::setImplicitlyInline
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2709
clang::CXXScopeSpec::location_data
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:219
clang::CXXRecordDecl::hasTrivialDefaultConstructor
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1209
clang::VarDecl::isLocalVarDeclOrParm
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1221
clang::CharUnits::isZero
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
getCanonicalDecl
static const Decl * getCanonicalDecl(const Decl *D)
Definition: IndexingContext.cpp:297
clang::DeclContext::addDecl
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1607
clang::ASTContext::getTagDeclType
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
Definition: ASTContext.cpp:5967
clang::FunctionProtoType
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4023
clang::Sema::AlignPackInfo::IsAlignAttr
bool IsAlignAttr() const
Definition: Sema.h:546
clang::DeclSpec::isMissingDeclaratorOk
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
Definition: DeclSpec.cpp:1451
clang::ASTContext::Idents
IdentifierTable & Idents
Definition: ASTContext.h:631
clang::Sema::CheckShadowingDeclModification
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
Definition: SemaDecl.cpp:8314
clang::Sema::inferObjCARCLifetime
bool inferObjCARCLifetime(ValueDecl *decl)
Definition: SemaDecl.cpp:6826
clang::FunctionDecl::isMultiVersion
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2519
clang::Declarator::getInventedTemplateParameterList
TemplateParameterList * getInventedTemplateParameterList() const
The template parameter list generated from the explicit template parameters along with any invented t...
Definition: DeclSpec.h:2568
clang::DeclContext::getParent
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1929
clang::Sema::shouldIgnoreInHostDeviceCheck
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
Definition: SemaDecl.cpp:19946
clang::CLanguageLinkage
@ CLanguageLinkage
Definition: Linkage.h:60
clang::Expr::getExprLoc
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:330
clang::Type::isIncompleteArrayType
bool isIncompleteArrayType() const
Definition: Type.h:6970
Specifier
const NestedNameSpecifier * Specifier
Definition: USRLocFinder.cpp:173
clang::MultiVersionKind::None
@ None
clang::ASTContext::getPrintingPolicy
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:684
clang::RecordDecl::fields
field_range fields() const
Definition: Decl.h:4223
clang::TypeLoc::getAs
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:88
FixInvalidVariablyModifiedTypeLoc
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
Definition: SemaDecl.cpp:6519
clang::TypeDecl::setTypeForDecl
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3271
clang::ElaboratedTypeLoc::setElaboratedKeywordLoc
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2270
clang::TypedefDecl::Create
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5171
clang::TemplateDecl
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:407
checkDLLAttributeRedeclaration
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
Definition: SemaDecl.cpp:7003
clang::LookupResult::Filter::done
void done()
Definition: Lookup.h:698
CheckMultiVersionValue
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target or target_version attribute of the function for MultiVersion validity.
Definition: SemaDecl.cpp:10853
clang::MangleNumberingContext::getStaticLocalNumber
virtual unsigned getStaticLocalNumber(const VarDecl *VD)=0
Static locals are numbered by source order.
clang::ASTContext::GE_Missing_type
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2190
clang::VarDecl::getDefinition
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2295
clang::VarDecl::getActingDefinition
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition: Decl.cpp:2274
clang::QualType::isNull
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:803
clang::Sema::ActOnFinishDelayedAttribute
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
Definition: SemaDecl.cpp:15844
clang::CallExpr::isCallToStdMove
bool isCallToStdMove() const
Definition: Expr.cpp:3458
llvm::ArrayRef
Definition: LLVM.h:31
clang::DeclSpec::TST_typename
static const TST TST_typename
Definition: DeclSpec.h:289
clang::Sema::setTagNameForLinkagePurposes
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:4962
Lexer.h
clang::LangAS::opencl_global
@ opencl_global
Value
Value
Definition: UninitializedValues.cpp:102
clang::Decl
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
clang::Builtin::Context::isInStdNamespace
bool isInStdNamespace(unsigned ID) const
Determines whether this builtin is a C++ standard library function that lives in (possibly-versioned)...
Definition: Builtins.h:182
clang::AttributeCommonInfo
Definition: AttributeCommonInfo.h:22
clang::Type::isClkEventT
bool isClkEventT() const
Definition: Type.h:7097
Scope.h
clang::ParmVarDecl::getFunctionScopeIndex
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1784
clang::Declarator::isFunctionDefinition
bool isFunctionDefinition() const
Definition: DeclSpec.h:2646
clang::DeclaratorDecl
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:767
clang::FunctionDecl::isPure
bool isPure() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2257
clang::TypeLoc
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:58
clang::Decl::isTemplated
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:262
clang::Expr::IgnoreParenImpCasts
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3036
clang::ASTContext::LongTy
CanQualType LongTy
Definition: ASTContext.h:1087
clang::Sema::CheckDestructorDeclarator
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
Definition: SemaDeclCXX.cpp:10693
HeaderSearch.h
clang::Sema::findLocallyScopedExternCDecl
NamedDecl * findLocallyScopedExternCDecl(DeclarationName Name)
Look for a locally scoped extern "C" declaration by the given name.
Definition: SemaDecl.cpp:6612
clang::DeclGroupRef
Definition: DeclGroup.h:51
clang::DeclSpec::TST_typeofType
static const TST TST_typeofType
Definition: DeclSpec.h:290
clang::DeclaratorChunk::Function
@ Function
Definition: DeclSpec.h:1200
clang::DeclarationNameInfo::setNamedTypeInfo
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
Definition: DeclarationName.h:816
clang::Sema::ActOnTypedefDeclarator
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
Definition: SemaDecl.cpp:6637
clang::Sema::mergeEnforceTCBAttr
EnforceTCBAttr * mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL)
Definition: SemaDeclAttr.cpp:8531
clang::DeclSpec::getInlineSpecLoc
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:590
clang::Sema::ActOnDeclarator
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6072
clang::Sema::Consumer
ASTConsumer & Consumer
Definition: Sema.h:410
clang::LCK_StarThis
@ LCK_StarThis
Capturing the *this object by copy.
Definition: Lambda.h:35
ComputeSelectedDestructor
static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record)
[class.dtor]p4: At the end of the definition of a class, overload resolution is performed among the p...
Definition: SemaDecl.cpp:18355
clang::QualType::isObjCGCWeak
bool isObjCGCWeak() const
true when Type is objc's weak.
Definition: Type.h:1184
clang::LanguageLinkage
LanguageLinkage
Describes the different kinds of language linkage (C++ [dcl.link]) that an entity may have.
Definition: Linkage.h:59
clang::ValueDecl::isInitCapture
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5046
clang::Sema
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:358
clang::FunctionDecl::TK_NonTemplate
@ TK_NonTemplate
Definition: Decl.h:1926
clang::ActionResult::isInvalid
bool isInvalid() const
Definition: Ownership.h:165
clang::DeclSpec::SCS_private_extern
@ SCS_private_extern
Definition: DeclSpec.h:241
clang::Sema::VerifyBitField
ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth)
VerifyBitField - verifies that a bit field expression is an ICE and has the correct width,...
Definition: SemaDecl.cpp:17731
clang::UnqualifiedIdKind::IK_DestructorName
@ IK_DestructorName
A destructor name.
clang::Decl::FOK_Declared
@ FOK_Declared
A friend of a previously-declared entity.
Definition: DeclBase.h:1177
clang::VarDecl::setInitStyle
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1404
clang::QualType::isPODType
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2398
clang::ASTContext::GE_None
@ GE_None
No error.
Definition: ASTContext.h:2187
clang::VarDecl::getTemplateSpecializationKind
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2675
clang::FunctionDefinitionKind::Definition
@ Definition
SDK_Using
@ SDK_Using
Definition: SemaDecl.cpp:8088
clang::SC_PrivateExtern
@ SC_PrivateExtern
Definition: Specifiers.h:241
clang::Qualifiers::addConst
void addConst()
Definition: Type.h:266
clang::DeclContextLookupResult::end
iterator end()
Definition: DeclBase.h:1349
clang::EnumDecl::Create
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4546
clang::QualType::DestructionKind
DestructionKind
Definition: Type.h:1276
clang::Sema::mergeErrorAttr
ErrorAttr * mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI, StringRef NewUserDiagnostic)
Definition: SemaDeclAttr.cpp:3874
clang::ASTContext::CharTy
CanQualType CharTy
Definition: ASTContext.h:1080
InvalidKernelParam
@ InvalidKernelParam
Definition: SemaDecl.cpp:9230
clang::TSK_ExplicitSpecialization
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:186
clang::interp::Ret
bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
Definition: Interp.h:159
clang::Type::getAsRecordDecl
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1787
clang::sema::FunctionScopeInfo::ObjCWarnForNoDesignatedInitChain
bool ObjCWarnForNoDesignatedInitChain
This starts true for a method marked as designated initializer and will be set to false if there is a...
Definition: ScopeInfo.h:156
clang::DeclSpec::TST_decltype
static const TST TST_decltype
Definition: DeclSpec.h:294
clang::Decl::attrs
attr_range attrs() const
Definition: DeclBase.h:519
clang::Declarator::isInvalidType
bool isInvalidType() const
Definition: DeclSpec.h:2627
AttrCompatibleWithMultiVersion
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:10903
clang::FunctionProtoType::getNumParams
unsigned getNumParams() const
Definition: Type.h:4234
clang::OR_Ambiguous
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
clang::Type::isPipeType
bool isPipeType() const
Definition: Type.h:7116
clang::ASTContext::attachCommentsToJustParsedDecls
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
Definition: ASTContext.cpp:558
clang::Sema::AddOverloadCandidate
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions=std::nullopt, OverloadCandidateParamOrder PO={})
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
Definition: SemaOverload.cpp:6423
clang::DeclaratorDecl::setQualifierInfo
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1928
clang::ASTContext::getTypeAlign
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2305
ASTConsumer.h
createFriendTagNNSFixIt
static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, SourceLocation NameLoc)
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:16550
clang::Type::isReserveIDT
bool isReserveIDT() const
Definition: Type.h:7105
clang::ParsedAttributes
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:1023
clang::Module::isModulePurview
bool isModulePurview() const
Does this Module scope describe part of the purview of a standard named C++ module?
Definition: Module.h:165
clang::RecordDecl::hasObjectMember
bool hasObjectMember() const
Definition: Decl.h:4078
clang::DeclContext::Encloses
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1244
clang::ASTContext::getObjCSelType
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2028
clang::LookupResult::getResultKind
LookupResultKind getResultKind() const
Definition: Lookup.h:321
clang::Sema::PushOnScopeChains
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1537
clang::DeclSpec::getConstexprSpecifier
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:777
clang::ParsedTargetAttr::CPU
StringRef CPU
Definition: TargetInfo.h:56
clang::Sema::CFT_Device
@ CFT_Device
Definition: Sema.h:13049
clang::Redeclarable::getMostRecentDecl
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
clang::DeclContext::isFileContext
bool isFileContext() const
Definition: DeclBase.h:1999
clang::ObjCMethodDecl::isOptional
bool isOptional() const
Definition: DeclObjC.h:506
clang::Sema::ContextRAII
A RAII object to temporarily push a declaration context.
Definition: Sema.h:1000
clang::NestedNameSpecifierLoc::getPrefix
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
Definition: NestedNameSpecifier.h:327
clang::sema::LambdaScopeInfo::IntroducerRange
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:842
clang::Sema::ActOnFileScopeAsmDecl
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: SemaDecl.cpp:19787
clang::DeclaratorChunk::getAttrs
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition: DeclSpec.h:1596
clang::AttributeCommonInfo::AS_Declspec
@ AS_Declspec
__declspec(...)
Definition: AttributeCommonInfo.h:36
clang::Sema::LookupSingleName
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration.
Definition: SemaLookup.cpp:3289
clang::sema::FunctionScopeInfo::isCoroutine
bool isCoroutine() const
Definition: ScopeInfo.h:487
clang::TemplateParameterList::size
unsigned size() const
Definition: DeclTemplate.h:131
clang::Sema::CurrentInstantiationScope
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:9790
PreviousDeclsHaveMultiVersionAttribute
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
Definition: SemaDecl.cpp:11143
clang::VarDecl::getInit
const Expr * getInit() const
Definition: Decl.h:1327
clang::FunctionType::ExtInfo
A class which abstracts out some details necessary for making a call.
Definition: Type.h:3793
clang::Sema::DiagnoseUnknownTypeName
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition: SemaDecl.cpp:720
getNextLargerIntegralType
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
Definition: SemaDecl.cpp:19067
clang::CXXRecordDecl::hasTrivialDestructor
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1335
clang::sema::TemplateDeductionInfo
Provides information about an attempted template argument deduction, whose success or failure was des...
Definition: TemplateDeduction.h:42
clang::Sema::CreateBuiltin
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
Definition: SemaDecl.cpp:2376
clang::RecordDecl::setNonTrivialToPrimitiveDestroy
void setNonTrivialToPrimitiveDestroy(bool V)
Definition: Decl.h:4116
clang::Expr::isValueDependent
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:170
clang::IdentifierInfo
One of these records is kept for each identifier that is lexed.
Definition: IdentifierTable.h:85
clang::Sema::areMultiversionVariantFunctionsCompatible
bool areMultiversionVariantFunctionsCompatible(const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer)
Checks if the variant/multiversion functions are compatible.
Definition: SemaDecl.cpp:10959
clang::Sema::getTemplateNameKindForDiagnostics
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1325
clang::transformer::member
RangeSelector member(std::string ID)
Given a MemberExpr, selects the member token.
Definition: RangeSelector.cpp:188
clang::Sema::IsAtLeastAsConstrained
bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef< const Expr * > AC1, NamedDecl *D2, MutableArrayRef< const Expr * > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
Definition: SemaConcept.cpp:1363
clang::FunctionDecl::isThisDeclarationInstantiatedFromAFriendDefinition
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3062
clang::TypedefDecl
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3390
clang::DeclaratorChunk::Kind
enum clang::DeclaratorChunk::@211 Kind
clang::FunctionDecl::setVirtualAsWritten
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition: Decl.h:2253
clang::ASTContext::getTargetInfo
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:744
clang::Expr::EvaluateAsInt
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
Definition: ExprConstant.cpp:15231
clang::RecordDecl::field_end
field_iterator field_end() const
Definition: Decl.h:4226
clang::OpaquePtr< QualType >::make
static OpaquePtr make(QualType P)
Definition: Ownership.h:60
clang::Sema::CheckMain
void CheckMain(FunctionDecl *FD, const DeclSpec &D)
Definition: SemaDecl.cpp:11949
clang::TypoCorrection::getCorrectionAsIdentifierInfo
IdentifierInfo * getCorrectionAsIdentifierInfo() const
Definition: TypoCorrection.h:86
clang::PartialDiagnostic::getDiagID
unsigned getDiagID() const
Definition: PartialDiagnostic.h:141
clang::Sema::mergeSectionAttr
SectionAttr * mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
Definition: SemaDeclAttr.cpp:3270
clang::DeclaratorChunk::MemberPointerTypeInfo::Scope
CXXScopeSpec & Scope()
Definition: DeclSpec.h:1553
clang::VarDecl::isPreviousDeclInSameBlockScope
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition: Decl.h:1544
clang::Sema::BuildDeclaratorGroup
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:14483
clang::PartialDiagnostic
Definition: PartialDiagnostic.h:31
clang::LangOptions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:82
clang::ASTContext::getElaboratedType
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
Definition: ASTContext.cpp:5109
clang::FunctionDecl::isExternC
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3307
clang::Type::isBooleanType
bool isBooleanType() const
Definition: Type.h:7320
clang::MemberPointerType
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2967
clang::VarDecl::getTSCSpec
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1136
clang::Decl::setObjectOfFriendDecl
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition: DeclBase.h:1145
clang::ParenTypeLoc::setRParenLoc
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1161
clang::ObjCPropertyAttribute::Kind
Kind
Definition: DeclObjCCommon.h:22
isDefaultStdCall
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
Definition: SemaDecl.cpp:12109
clang::Sema::SemaDiagnosticBuilder
A generic diagnostic builder for errors which may or may not be deferred.
Definition: Sema.h:1770
clang::BinaryConditionalOperator::getFalseExpr
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condnition evaluates to false;...
Definition: Expr.h:4269
clang::DeclContext::getInnermostBlockDecl
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
Definition: DeclBase.cpp:1141
clang::TemplateParameterList::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:197
clang::InitializationKind
Describes the kind of initialization being performed, along with location information for tokens rela...
Definition: Initialization.h:566
clang::Sema::getObjCInterfaceDecl
ObjCInterfaceDecl * getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection=false)
Look for an Objective-C class in the translation unit.
Definition: SemaDecl.cpp:2302
clang::ASTContext::hasSameFunctionTypeIgnoringExceptionSpec
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
Definition: ASTContext.cpp:3297
clang::Sema::mergeTypeVisibilityAttr
TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis)
Definition: SemaDeclAttr.cpp:2874
clang::ActionResult
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc.
Definition: Ownership.h:152
SDK_Local
@ SDK_Local
Definition: SemaDecl.cpp:8083
clang::Type::isObjCObjectType
bool isObjCObjectType() const
Definition: Type.h:7028
clang::ArrayTypeLoc
Wrapper for source info for arrays.
Definition: TypeLoc.h:1516
shouldWarnIfShadowedDecl
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
Definition: SemaDecl.cpp:8118
clang::DeclSpec::getRepAsDecl
Decl * getRepAsDecl() const
Definition: DeclSpec.h:509
clang::FunctionTemplateDecl::getTemplatedDecl
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Definition: DeclTemplate.h:1051
checkAttributesAfterMerging
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6911
clang::MangleNumberingContext
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
Definition: MangleNumberingContext.h:29
clang::ConstantArrayType::getNumAddressingBits
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition: Type.cpp:141
clang::ElaboratedTypeLoc
Definition: TypeLoc.h:2261
clang::DeclFilterCCC
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
Definition: TypoCorrection.h:366
clang::Sema::getEmissionStatus
FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl, bool Final=false)
Definition: SemaDecl.cpp:19866
clang::TypeLoc::IgnoreParens
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1183
clang::NamespaceDecl::isAnonymousNamespace
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:602
clang::Sema::mergeMSInheritanceAttr
MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model)
Definition: SemaDeclAttr.cpp:7944
DiagnoseInvalidRedeclaration
static NamedDecl * DiagnoseInvalidRedeclaration(Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S)
Generate diagnostics for an invalid function redeclaration.
Definition: SemaDecl.cpp:8863
clang::ASTContext::setjmp_bufDecl
void setjmp_bufDecl(TypeDecl *jmp_bufDecl)
Set the type for the C jmp_buf type.
Definition: ASTContext.h:1918
clang::Decl::hasOwningModule
bool hasOwningModule() const
Is this declaration owned by some module?
Definition: DeclBase.h:803
clang::sema::LambdaScopeInfo
Definition: ScopeInfo.h:832
clang::ObjCMethodDecl
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:138
clang::TargetInfo::getShortWidth
unsigned getShortWidth() const
Return the size of 'signed short' and 'unsigned short' for this target, in bits.
Definition: TargetInfo.h:469
clang::Type::isEventT
bool isEventT() const
Definition: Type.h:7093
clang::PointerType
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2776
clang::RecordDecl::setNonTrivialToPrimitiveDefaultInitialize
void setNonTrivialToPrimitiveDefaultInitialize(bool V)
Definition: Decl.h:4100
clang::Sema::mergeImportModuleAttr
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
Definition: SemaDeclAttr.cpp:7558
clang::TST_class
@ TST_class
Definition: Specifiers.h:79
ScopeInfo.h
clang::Sema::CheckStaticLocalForDllExport
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
Definition: SemaDecl.cpp:14194
clang::Builtin::Context::isTSBuiltin
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:111
clang::ast_matchers::recordType
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
Definition: ASTMatchersInternal.cpp:1061
clang::DeclSpec::TST_unspecified
static const TST TST_unspecified
Definition: DeclSpec.h:261
clang::LangAS::Default
@ Default
clang::FunctionDecl::isMSVCRTEntryPoint
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3158
isRecordType
static bool isRecordType(QualType T)
Definition: SemaExprMember.cpp:1216
clang::DecompositionDeclarator
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition: DeclSpec.h:1725
clang::DeclaratorDecl::setTypeSourceInfo
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:802
clang::Type::getBaseElementTypeUnsafe
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:7360
clang::Qualifiers::OCL_None
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:163
clang::VarDecl::isExternC
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition: Decl.cpp:2174
clang::Type::isHalfType
bool isHalfType() const
Definition: Type.h:7208
clang::BinaryOperator::isCompoundAssignmentOp
static bool isCompoundAssignmentOp(Opcode Opc)
Definition: Expr.h:3955
clang::PointerLikeTypeLoc::getPointeeLoc
TypeLoc getPointeeLoc() const
Definition: TypeLoc.h:1240
clang::Sema::CheckEnumRedeclaration
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev)
Check whether this is a valid redeclaration of a previous enumeration.
Definition: SemaDecl.cpp:16337
clang::FunctionDecl::isMain
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3150
clang::ObjCMethodDecl::param_begin
param_const_iterator param_begin() const
Definition: DeclObjC.h:356
clang::sema::CapturingScopeInfo::ImpCap_LambdaByref
@ ImpCap_LambdaByref
Definition: ScopeInfo.h:675
clang::TargetInfo::isValidFeatureName
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
Definition: TargetInfo.h:1331
clang::FileScopeAsmDecl
Definition: Decl.h:4269
clang::FunctionDecl::isLateTemplateParsed
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition: Decl.h:2261
clang::Sema::BuildMicrosoftCAnonymousStruct
Decl * BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record)
BuildMicrosoftCAnonymousStruct - Handle the declaration of an Microsoft C anonymous structure.
Definition: SemaDecl.cpp:5761
clang::DeclaratorContext::TypeName
@ TypeName
clang::Sema::FunctionEmissionStatus::Emitted
@ Emitted
clang::Type::castAsArrayTypeUnsafe
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: Type.h:7486
clang::VarDecl::TLS_Dynamic
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:941
clang::ASTContext::getParenType
QualType getParenType(QualType NamedType) const
Definition: ASTContext.cpp:5139
isResultTypeOrTemplate
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition: SemaDecl.cpp:835
clang::VarDecl::ParenListInit
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition: Decl.h:929
clang::CXXConstructorDecl::isCopyConstructor
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition: DeclCXX.cpp:2693
clang::FunctionType::ExtInfo::getRegParm
unsigned getRegParm() const
Definition: Type.h:3848
clang::RecordDecl::reorderDecls
void reorderDecls(const SmallVectorImpl< Decl * > &Decls)
Definition: Decl.cpp:4793
clang::ASTContext::getAddrSpaceQualType
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
Definition: ASTContext.cpp:3139
clang::FunctionTemplateDecl::getPreviousDecl
FunctionTemplateDecl * getPreviousDecl()
Retrieve the previous declaration of this function template, or nullptr if no such declaration exists...
Definition: DeclTemplate.h:1077
clang::ParsedTargetAttr::Features
std::vector< std::string > Features
Definition: TargetInfo.h:55
clang::CXXMethodDecl::addOverriddenMethod
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition: DeclCXX.cpp:2452
clang::Sema::isDeclInScope
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false)
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
Definition: SemaDecl.cpp:1595
clang::IdentifierInfo::getName
StringRef getName() const
Return the actual identifier string.
Definition: IdentifierTable.h:196
clang::Builtin::ID
ID
Definition: Builtins.h:64
clang::Sema::CheckParameter
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:14760
clang::LinkageSpecDecl::Create
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:2851
clang::FunctionProtoType::ExtProtoInfo
Extra information about a function prototype.
Definition: Type.h:4106
clang::CXXBasePath
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
Definition: CXXInheritance.h:70
clang::SourceLocation::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:111
clang::CXXMethodDecl::isConst
bool isConst() const
Definition: DeclCXX.h:2036
clang::Sema::CheckCompleteVariableDeclaration
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:13896
clang::UnaryOperator::getSubExpr
Expr * getSubExpr() const
Definition: Expr.h:2222
clang::ObjCIvarDecl::Create
static ObjCIvarDecl * Create(ASTContext &C, ObjCContainerDecl *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW=nullptr, bool synthesized=false)
Definition: DeclObjC.cpp:1839
clang::FieldDecl::getParent
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3135
clang::Expr::IgnoreParens
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3032
clang::Sema::LookupNestedNameSpecifierName
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition: Sema.h:4307
PartialDiagnostic.h
clang::TSCS__Thread_local
@ TSCS__Thread_local
C11 _Thread_local.
Definition: Specifiers.h:232
clang::Sema::mergeDeclAttributes
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3168
clang
Definition: CalledOnceCheck.h:17
clang::Type::isAnyPointerType
bool isAnyPointerType() const
Definition: Type.h:6900
clang::Sema::CFT_Global
@ CFT_Global
Definition: Sema.h:13050
clang::LangOptions::MSVC2015
@ MSVC2015
Definition: LangOptions.h:146
clang::TemplateArgumentListInfo::setRAngleLoc
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:610
clang::IndirectFieldDecl
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3197
clang::Sema::mergeObjCMethodDecls
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
Definition: SemaDecl.cpp:4341
clang::DeclContext::lookup
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1693
clang::Sema::OffsetOfKind
OffsetOfKind
Definition: Sema.h:3314
clang::Type::isDependentSizedArrayType
bool isDependentSizedArrayType() const
Definition: Type.h:6978
clang::Sema::ImplicitlyRetainedSelfLocs
llvm::SmallVector< std::pair< SourceLocation, const BlockDecl * >, 1 > ImplicitlyRetainedSelfLocs
List of SourceLocations where 'self' is implicitly retained inside a block.
Definition: Sema.h:1542
clang::DeclarationNameInfo::setLoc
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
Definition: DeclarationName.h:799
clang::FunctionDecl::setHasSkippedBody
void setHasSkippedBody(bool Skipped=true)
Definition: Decl.h:2510
clang::Decl::OBJC_TQ_CSNullability
@ OBJC_TQ_CSNullability
The nullability qualifier is set when the nullability of the result or parameter was expressed via a ...
Definition: DeclBase.h:207
clang::VarDecl::DeclarationOnly
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1254
clang::QualType::withoutLocalFastQualifiers
QualType withoutLocalFastQualifiers() const
Definition: Type.h:971
clang::Type::isArrayType
bool isArrayType() const
Definition: Type.h:6962
clang::Sema::checkVarDeclRedefinition
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn)
We've just determined that Old and New both appear to be definitions of the same variable.
Definition: SemaDecl.cpp:4805
clang::ASTContext::toCharUnitsFromBits
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
Definition: ASTContext.cpp:2549
clang::UnqualifiedIdKind::IK_ConversionFunctionId
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
clang::TargetInfo::allowDebugInfoForExternalRef
virtual bool allowDebugInfoForExternalRef() const
Whether target allows debuginfo types for decl only variables/functions.
Definition: TargetInfo.h:1687
clang::FunctionDecl::setDescribedFunctionTemplate
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:3814
clang::Sema::ActOnEnumBody
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
Definition: SemaDecl.cpp:19550
clang::NestedNameSpecifier::getAsType
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
Definition: NestedNameSpecifier.h:196
clang::Builtin::Context
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition: Builtins.h:85
clang::Sema::ActOnTagStartSkippedDefinition
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD)
Invoked when we enter a tag definition that we're skipping.
Definition: SemaDecl.cpp:1358
clang::CXXBaseSpecifier::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclCXX.h:191
clang::DeclSpec::TST_atomic
static const TST TST_atomic
Definition: DeclSpec.h:302
clang::Sema::ActOnDocumentableDecl
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:14523
clang::FunctionTemplateDecl::getInstantiatedFromMemberTemplate
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
Definition: DeclTemplate.h:1095
clang::Qualifiers::getObjCLifetime
ObjCLifetime getObjCLifetime() const
Definition: Type.h:351
clang::GVA_AvailableExternally
@ GVA_AvailableExternally
Definition: Linkage.h:70
clang::DeclaratorContext::Block
@ Block
isAttributeTargetADefinition
static bool isAttributeTargetADefinition(Decl *D)
Definition: SemaDecl.cpp:2752
clang::ExternalLinkage
@ ExternalLinkage
External linkage, which indicates that the entity can be referred to from other translation units.
Definition: Linkage.h:54
clang::Sema::CheckConstructorDeclarator
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
Definition: SemaDeclCXX.cpp:10540
checkNonMultiVersionCompatAttributes
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:10918
clang::Stmt
Stmt - This represents one statement.
Definition: Stmt.h:72
clang::EST_BasicNoexcept
@ EST_BasicNoexcept
noexcept
Definition: ExceptionSpecificationType.h:26
clang::ObjCIvarDecl
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1939
clang::QualType::isNonTrivialToPrimitiveCopy
PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition: Type.cpp:2600
clang::Sema::RegisterLocallyScopedExternCDecl
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S)
Register the given locally-scoped extern "C" declaration so that it can be found later for redeclarat...
Definition: SemaDecl.cpp:6602
clang::Scope::getEntity
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition: Scope.h:360
clang::VarDecl::isConstexpr
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1521
clang::UnaryOperator::getOpcode
Opcode getOpcode() const
Definition: Expr.h:2217
clang::BinaryOperator::getRHS
Expr * getRHS() const
Definition: Expr.h:3866
clang::Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
Definition: SemaDecl.cpp:15990
clang::ASTContext::SignedCharTy
CanQualType SignedCharTy
Definition: ASTContext.h:1087
clang::TemplateIdAnnotation::getTemplateArgs
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
Definition: ParsedTemplate.h:192
clang::Sema::isIncompatibleTypedef
bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New)
Definition: SemaDecl.cpp:2521
clang::Declarator::isCtorOrDtor
bool isCtorOrDtor()
Returns true if this declares a constructor or a destructor.
Definition: DeclSpec.cpp:423
clang::Builtin::Context::allowTypeMismatch
bool allowTypeMismatch(unsigned ID) const
Determines whether a declaration of this builtin should be recognized even if the type doesn't match ...
Definition: Builtins.h:202
clang::CXXRecordDecl::getCanonicalDecl
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:507
clang::Declarator
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1834
clang::Sema::CheckEnumUnderlyingType
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
Definition: SemaDecl.cpp:16316
clang::SourceManager::isInSystemHeader
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
Definition: SourceManager.h:1507
clang::sema::LambdaScopeInfo::ShadowingDecls
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition: ScopeInfo.h:911
clang::Type::isDependentAddressSpaceType
bool isDependentAddressSpaceType() const
Definition: Type.h:7020
clang::Sema::getObjCDeclContext
ObjCContainerDecl * getObjCDeclContext() const
Definition: SemaDecl.cpp:19862
clang::NestedNameSpecifierLoc::getNestedNameSpecifier
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
Definition: NestedNameSpecifier.h:274
clang::EnumDecl::getIntegerType
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:3878
clang::CXXRecordDecl::bases_begin
base_class_iterator bases_begin()
Definition: DeclCXX.h:609
clang::LookupResult::Filter
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:643
clang::Sema::getImplicitCodeSegOrSectionAttrForFunction
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
Definition: SemaDecl.cpp:10768
clang::TypoCorrection::getCorrectionDecl
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
Definition: TypoCorrection.h:151
clang::Sema::ActOnPragmaWeakAlias
void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
Definition: SemaDecl.cpp:19844
clang::ElaboratedTypeLoc::setQualifierLoc
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2284
clang::QualType::isNonTrivialToPrimitiveDefaultInitialize
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition: Type.cpp:2584
clang::Expr::getType
QualType getType() const
Definition: Expr.h:143
PtrKernelParam
@ PtrKernelParam
Definition: SemaDecl.cpp:9228
Randstruct.h
clang::CXXScopeSpec::getScopeRep
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:78
clang::SourceLocation::isValid
bool isValid() const
Return true if this is a valid SourceLocation object.
Definition: SourceLocation.h:110
clang::LangOptions::FPE_Ignore
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Definition: LangOptions.h:272
clang::Builtin::Context::isPure
bool isPure(unsigned ID) const
Return true if this function has no side effects.
Definition: Builtins.h:116
clang::DeclAttrsMatchCUDAMode
bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
Definition: SemaInternal.h:44
clang::CXXBaseSpecifier
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
clang::CorrectionCandidateCallback
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
Definition: TypoCorrection.h:281
clang::Sema::getCallingConvAttributedType
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
Definition: SemaDecl.cpp:3484
clang::Attr
Attr - This represents one attribute.
Definition: Attr.h:40
clang::CXXRecordDecl::hasDefinition
bool hasDefinition() const
Definition: DeclCXX.h:555
clang::LookupResult::Found
@ Found
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
clang::TypeSourceInfo
A container of type source information.
Definition: Type.h:6606
PtrPtrKernelParam
@ PtrPtrKernelParam
Definition: SemaDecl.cpp:9227
clang::FunctionType::getReturnType
QualType getReturnType() const
Definition: Type.h:3947
clang::SourceManager::getFileEntryForID
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
Definition: SourceManager.h:1046
clang::NamedDecl::getDeclName
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:313
clang::DefaultInitializedTypeVisitor
Definition: NonTrivialTypeVisitor.h:50
clang::FixItHint::CreateRemoval
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
clang::DeclSpec::getTypeQualifiers
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:567
clang::Declarator::getTypeObject
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2303
InvalidAddrSpacePtrKernelParam
@ InvalidAddrSpacePtrKernelParam
Definition: SemaDecl.cpp:9229
getFunctionStorageClass
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
Definition: SemaDecl.cpp:9014
clang::TargetInfo::supportsMultiVersioning
bool supportsMultiVersioning() const
Identify whether this target supports multiversioning of functions, which requires support for cpu_su...
Definition: TargetInfo.h:1388
clang::DeclContext::isDependentContext
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1174
clang::MultiVersionKind::CPUSpecific
@ CPUSpecific
clang::LookupResult::getLookupKind
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:253
clang::Scope::RemoveDecl
void RemoveDecl(Decl *D)
Definition: Scope.h:329
clang::Sema::ActOnTagStartDefinition
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
Definition: SemaDecl.cpp:17567
unsigned
clang::DeclSpec::isVirtualSpecified
bool isVirtualSpecified() const
Definition: DeclSpec.h:598
clang::Builtin::Context::isHeaderDependentFunction
bool isHeaderDependentFunction(unsigned ID) const
Returns true if this builtin requires appropriate header in other compilers.
Definition: Builtins.h:167
clang::SC_Auto
@ SC_Auto
Definition: Specifiers.h:244
clang::FunctionProtoType::ExtProtoInfo::TypeQuals
Qualifiers TypeQuals
Definition: Type.h:4110
clang::Stmt::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:337
clang::sema::CapturingScopeInfo::addThisCapture
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition: ScopeInfo.h:1054
adjustDeclContextForDeclaratorDecl
static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, DeclaratorDecl *OldD)
If necessary, adjust the semantic declaration context for a qualified declaration to name the correct...
Definition: SemaDecl.cpp:3566
clang::Sema::checkNonTrivialCUnion
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
Definition: SemaDecl.cpp:12980
clang::Sema::adjustContextForLocalExternDecl
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7244
clang::Sema::ActOnFunctionDeclarator
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
Definition: SemaDecl.cpp:9576
clang::DeclaratorChunk
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1196
clang::RecordDecl::isMsStruct
bool isMsStruct(const ASTContext &C) const
Get whether or not this is an ms_struct which can be turned on with an attribute, pragma,...
Definition: Decl.cpp:4789
clang::FunctionDecl::hasInheritedPrototype
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition: Decl.h:2356
clang::FunctionDecl::isExplicitlyDefaulted
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2286
clang::VarDecl::Definition
@ Definition
This declaration is definitely a definition.
Definition: Decl.h:1260
clang::TSCS___thread
@ TSCS___thread
GNU __thread.
Definition: Specifiers.h:226
clang::NestedNameSpecifierLocBuilder::MakeTrivial
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: NestedNameSpecifier.cpp:631
clang::InitializedEntity
Describes an entity that is being initialized.
Definition: Initialization.h:47
clang::FunctionDecl::isVariadic
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3006
clang::PointerTypeLoc::setStarLoc
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1265
clang::Type::isConstantArrayType
bool isConstantArrayType() const
Definition: Type.h:6966
MultiVersionTypesCompatible
static bool MultiVersionTypesCompatible(MultiVersionKind Old, MultiVersionKind New)
Definition: SemaDecl.cpp:11257
clang::ASTContext::setsigjmp_bufDecl
void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl)
Set the type for the C sigjmp_buf type.
Definition: ASTContext.h:1930
clang::AttributeCommonInfo::AS_Pragma
@ AS_Pragma
#pragma ...
Definition: AttributeCommonInfo.h:45
CheckMultiVersionFunction
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a mulitversion function declaration.
Definition: SemaDecl.cpp:11493
clang::TagDecl::getTagKind
TagKind getTagKind() const
Definition: Decl.h:3633
clang::Sema::ExitDeclaratorContext
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1414
clang::InitializedEntity::InitializeVariable
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
Definition: Initialization.h:248
clang::Sema::ActOnTopLevelStmtDecl
Decl * ActOnTopLevelStmtDecl(Stmt *Statement)
Definition: SemaDecl.cpp:19799
clang::TypedefNameDecl
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3288
clang::FunctionDecl::param_begin
param_iterator param_begin()
Definition: Decl.h:2596
clang::ParenListExpr::getExprs
Expr ** getExprs()
Definition: Expr.h:5421
clang::Decl::getAttrs
AttrVec & getAttrs()
Definition: DeclBase.h:508
CheckForDuplicateEnumValues
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
Definition: SemaDecl.cpp:19411
clang::LookupResult::getFoundDecl
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:543
clang::LookupResult::getAsSingle
DeclClass * getAsSingle() const
Definition: Lookup.h:533
clang::Sema::getTypeName
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition: SemaDecl.cpp:328
CheckMultiVersionAdditionalRules
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, const FunctionDecl *NewFD, bool CausesMV, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11072
clang::Sema::AMK_ProtocolImplementation
@ AMK_ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition: Sema.h:3603
clang::TargetOptions::HLSLEntry
std::string HLSLEntry
The entry point name for HLSL shader being compiled as specified by -E.
Definition: TargetOptions.h:118
clang::ObjCContainerDecl
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:941
clang::ASTContext::addDeclaratorForUnnamedTagDecl
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
Definition: ASTContext.cpp:12152
clang::DeclContextLookupResult
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1334
clang::Token::isOneOf
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:100
clang::DependentNameTypeLoc::setNameLoc
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2370
clang::DeclaratorContext::KNRTypeList
@ KNRTypeList
clang::ASTContext::mergeObjCGCQualifiers
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
Definition: ASTContext.cpp:10906
ValidKernelParam
@ ValidKernelParam
Definition: SemaDecl.cpp:9226
clang::DeclaratorDecl::getNumTemplateParameterLists
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:855
clang::Sema::CheckTypedefForVariablyModifiedType
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6684
clang::ImplicitCastExpr
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3627
clang::ArrayTypeLoc::getLBracketLoc
SourceLocation getLBracketLoc() const
Definition: TypeLoc.h:1521
clang::TU_Complete
@ TU_Complete
The translation unit is a complete translation unit.
Definition: LangOptions.h:919
isExternC
static bool isExternC(T *D)
Definition: SemaDecl.cpp:3505
clang::DeclSpec::TST_struct
static const TST TST_struct
Definition: DeclSpec.h:286
clang::Sema::ParseTypedefDecl
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
Definition: SemaDecl.cpp:16259
clang::Sema::mergeEnforceTCBLeafAttr
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
Definition: SemaDeclAttr.cpp:8536
clang::Sema::AlignPackInfo::getAlignMode
Mode getAlignMode() const
Definition: Sema.h:548
clang::Sema::handleTagNumbering
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
Definition: SemaDecl.cpp:4852
clang::MemberExpr
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3172
clang::TypeLoc::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:152
clang::DeclSpec::TQ_restrict
@ TQ_restrict
Definition: DeclSpec.h:312
clang::CXXBasePaths
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Definition: CXXInheritance.h:117
clang::ASTContext::getTrivialTypeSourceInfo
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
Definition: ASTContext.cpp:3075
clang::ConstraintSatisfaction
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:28
clang::CXXRecordDecl::hasNonTrivialDestructor
bool hasNonTrivialDestructor() const
Determine whether this class has a non-trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1345
clang::DeclaratorChunk::ParamInfo::IdentLoc
SourceLocation IdentLoc
Definition: DeclSpec.h:1276
clang::Builtin::Context::isScanfLike
bool isScanfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like scanf in its formatting rules and, if so, set the index to the...
Definition: Builtins.cpp:204
clang::InClassInitStyle
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:259
clang::QualType::getTypePtr
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6635
clang::RecordType::getDecl
RecordDecl * getDecl() const
Definition: Type.h:4833
clang::Attr::setImplicit
void setImplicit(bool I)
Definition: Attr.h:94
clang::NestedNameSpecifier::GlobalSpecifier
static NestedNameSpecifier * GlobalSpecifier(const ASTContext &Context)
Returns the nested name specifier representing the global scope.
Definition: NestedNameSpecifier.cpp:126
clang::Sema::DiagnoseUnusedParameters
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
Definition: SemaDecl.cpp:14719
clang::ASTContext::getPointerType
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
Definition: ASTContext.cpp:3386
clang::DeclSpec::TQ_const
@ TQ_const
Definition: DeclSpec.h:311
clang::CPlusPlus11
@ CPlusPlus11
Definition: LangStandard.h:54
clang::ETK_Typename
@ ETK_Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition: Type.h:5584
getCoreType
static QualType getCoreType(QualType Ty)
Definition: SemaDecl.cpp:5927
clang::CXXScopeSpec::MakeTrivial
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:126
clang::NamedDecl::isCXXClassMember
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:369
clang::Sema::ShouldWarnIfUnusedFileScopedDecl
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
Definition: SemaDecl.cpp:1885
CheckMultiVersionAdditionalDecl
static bool CheckMultiVersionAdditionalDecl(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, MultiVersionKind NewMVKind, const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a new function declaration being added to an existing multiversioned declaratio...
Definition: SemaDecl.cpp:11271
getDefinition
static const NamedDecl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:2974
clang::QualType::PrimitiveDefaultInitializeKind
PrimitiveDefaultInitializeKind
Definition: Type.h:1209
Parent
NodeId Parent
Definition: ASTDiff.cpp:191
clang::ReferenceType
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2887
clang::CharUnits
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
clang::DeclSpec::getModulePrivateSpecLoc
SourceLocation getModulePrivateSpecLoc() const
Definition: DeclSpec.h:775
clang::PointerType::getPointeeType
QualType getPointeeType() const
Definition: Type.h:2786
clang::Sema::DiagnoseUnusedDecl
void DiagnoseUnusedDecl(const NamedDecl *ND)
Definition: SemaDecl.cpp:2114
clang::TypeLoc::initializeFullCopy
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition: TypeLoc.h:202
clang::LookupResult::getSema
Sema & getSema() const
Get the Sema object that this lookup result is searching with.
Definition: Lookup.h:638
clang::Sema::CXXSpecialMember
CXXSpecialMember
Kinds of C++ special members.
Definition: Sema.h:1545
checkGlobalOrExternCConflict
static bool checkGlobalOrExternCConflict(Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous)
Check for conflict between this global or extern "C" declaration and previous global or extern "C" de...
Definition: SemaDecl.cpp:8339
clang::Sema::CheckVariableDeclaration
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
Definition: SemaDecl.cpp:8721
lookupUnqualifiedTypeNameInBase
static UnqualifiedTypeNameLookupResult lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc, const CXXRecordDecl *RD)
Tries to perform unqualified lookup of the type decls in bases for dependent class.
Definition: SemaDecl.cpp:186
clang::InheritedConstructor
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2422
clang::Decl::setInvalidDecl
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
clang::VarDecl::hasDependentAlignment
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition: Decl.cpp:2602
clang::Sema::CheckEnumConstant
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
Definition: SemaDecl.cpp:19091
clang::OverloadCandidateSet::begin
iterator begin()
Definition: Overload.h:1126
SDK_Global
@ SDK_Global
Definition: SemaDecl.cpp:8084
clang::FunctionDecl::isFunctionTemplateSpecialization
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.h:2797
clang::CXXConstructExpr::getArg
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1669
clang::isTemplateInstantiation
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:200
clang::ASTContext::hasSameType
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2516
clang::ObjCRuntime::isNonFragile
bool isNonFragile() const
Does this runtime follow the set of implied behaviors for a "non-fragile" ABI?
Definition: ObjCRuntime.h:82
clang::DestructedTypeVisitor
Definition: NonTrivialTypeVisitor.h:21
clang::IndirectFieldDecl::Create
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, llvm::MutableArrayRef< NamedDecl * > CH)
Definition: Decl.cpp:5149
clang::Sema::LookupOrdinaryName
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:4288
clang::VarDecl::setStorageClass
void setStorageClass(StorageClass SC)
Definition: Decl.cpp:2091
clang::TypeLoc::castAs
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:77
clang::Sema::CXXCopyAssignment
@ CXXCopyAssignment
Definition: Sema.h:1549
clang::DeclSpec::TST_typeofExpr
static const TST TST_typeofExpr
Definition: DeclSpec.h:291
getMSManglingNumber
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
Definition: SemaDecl.cpp:4846
clang::Declarator::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclSpec.h:2006
clang::Sema::BuildParmVarDeclForTypedef
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:14706
clang::NestedNameSpecifierLoc::getTypeLoc
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
Definition: NestedNameSpecifier.cpp:453
llvm::SmallVectorImpl
Definition: Randstruct.h:18
clang::ASTContext::setObjCIdRedefinitionType
void setObjCIdRedefinitionType(QualType RedefType)
Set the user-written type that redefines id.
Definition: ASTContext.h:1826
clang::EnumDecl::isClosedFlag
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition: Decl.cpp:4591
clang::sema::AnalysisBasedWarnings::Policy::disableCheckFallThrough
void disableCheckFallThrough()
Definition: AnalysisBasedWarnings.h:42
clang::Type::getNullability
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4182
clang::Scope::DeclScope
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:60
clang::CXXRecordDecl::hasUserDeclaredDestructor
bool hasUserDeclaredDestructor() const
Determine whether this class has a user-declared destructor.
Definition: DeclCXX.h:988
clang::CallExpr::arguments
arg_range arguments()
Definition: Expr.h:3052
clang::ASTContext::setucontext_tDecl
void setucontext_tDecl(TypeDecl *ucontext_tDecl)
Set the type for the C ucontext_t type.
Definition: ASTContext.h:1942
clang::FunctionDecl::isTemplateInstantiation
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:3867
clang::Sema::HandleDeclarator
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:6225
clang::InheritableParamAttr
Definition: Attr.h:176
clang::Builtin::Context::isPrintfLike
bool isPrintfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like printf in its formatting rules and, if so, set the index to th...
Definition: Builtins.cpp:199
ComputeSpecialMemberFunctionsEligiblity
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, CXXRecordDecl *Record)
Definition: SemaDecl.cpp:18510
clang::Lexer::findLocationAfterToken
static SourceLocation findLocationAfterToken(SourceLocation loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine)
Checks that the given token is the first token that occurs after the given location (this excludes co...
Definition: Lexer.cpp:1294
clang::SC_None
@ SC_None
Definition: Specifiers.h:238
clang::ValueDecl::getType
QualType getType() const
Definition: Decl.h:714
checkDuplicateDefaultInit
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
Definition: SemaDecl.cpp:5455
clang::Type::isFunctionReferenceType
bool isFunctionReferenceType() const
Definition: Type.h:6937
clang::DeducedType
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5219
clang::FunctionDecl::getBuiltinID
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3413
clang::RecordDecl::setParamDestroyedInCallee
void setParamDestroyedInCallee(bool V)
Definition: Decl.h:4163
clang::VarTemplateDecl
Declaration of a variable template.
Definition: DeclTemplate.h:3119
clang::EvaluatedExprVisitor
EvaluatedExprVisitor - This class visits 'Expr *'s.
Definition: EvaluatedExprVisitor.h:128
clang::ASTContext::hasSameUnqualifiedType
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2543
clang::ASTContext::setStaticLocalNumber
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
Definition: ASTContext.cpp:12095
clang::Sema::mergeOptimizeNoneAttr
OptimizeNoneAttr * mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI)
Definition: SemaDeclAttr.cpp:4879
clang::GNUMode
@ GNUMode
Definition: LangStandard.h:60
clang::Sema::ParsingInitForAutoVars
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:872
clang::ArrayType::getElementType
QualType getElementType() const
Definition: Type.h:3040
Previous
StateNode * Previous
Definition: UnwrappedLineFormatter.cpp:1149
clang::ASTContext::getOverloadedTemplateName
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
Definition: ASTContext.cpp:9226
clang::ParsedAttributes::getPool
AttributePool & getPool() const
Definition: ParsedAttr.h:1028
clang::ParsedAttributesView
Definition: ParsedAttr.h:920
clang::Expr
This represents one expression.
Definition: Expr.h:111
clang::FunctionType::getRegParmType
unsigned getRegParmType() const
Definition: Type.h:3950
clang::HLSL
@ HLSL
Definition: LangStandard.h:63
clang::Sema::CheckFunctionOrTemplateParamDeclarator
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D)
Common checks for a parameter-declaration that should apply to both function parameters and non-type ...
Definition: SemaDecl.cpp:14560
clang::CXXScopeSpec::isEmpty
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:191
clang::sema::Capture::getVariable
ValueDecl * getVariable() const
Definition: ScopeInfo.h:646
FindPossiblePrototype
static bool FindPossiblePrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:14930
clang::TargetInfo::shouldDLLImportComdatSymbols
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1228
clang::FunctionDecl::getDescribedFunctionTemplate
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:3809
SM
#define SM(sm)
Definition: Cuda.cpp:78
clang::Sema::SkipBodyInfo::Previous
NamedDecl * Previous
Definition: Sema.h:2588
clang::ModuleLinkage
@ ModuleLinkage
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition: Linkage.h:50
clang::IdentifierResolver::iterator
iterator - Iterate over the decls of a specified declaration name.
Definition: IdentifierResolver.h:69
clang::ParmVarDecl::Create
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2834
clang::Declarator::getAttributes
const ParsedAttributes & getAttributes() const
Definition: DeclSpec.h:2588
clang::ASTContext::getExternCContextDecl
ExternCContextDecl * getExternCContextDecl() const
Definition: ASTContext.cpp:1249
clang::UnqualifiedId::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1182
clang::LabelDecl::isMSAsmLabel
bool isMSAsmLabel() const
Definition: Decl.h:530
clang::RecordDecl::Create
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:4709
clang::RecordDecl::setNonTrivialToPrimitiveCopy
void setNonTrivialToPrimitiveCopy(bool V)
Definition: Decl.h:4108
clang::QualType::isDestructedType
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1288
clang::VarDecl::hasLocalStorage
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1143
clang::CXXScopeSpec::getRange
SourceRange getRange() const
Definition: DeclSpec.h:70
clang::NestedNameSpecifier::getKind
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
Definition: NestedNameSpecifier.cpp:143
clang::sema::Capture::isVariableCapture
bool isVariableCapture() const
Definition: ScopeInfo.h:621
clang::Decl::dropAttrs
void dropAttrs()
Definition: DeclBase.cpp:896
OpenCLParamType
OpenCLParamType
Definition: SemaDecl.cpp:9225
clang::DeclSpec::SetRangeEnd
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:659
clang::MultiVersionKind
MultiVersionKind
Definition: Decl.h:1898
clang::TSK_ImplicitInstantiation
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:182
clang::Sema::canSkipFunctionBody
bool canSkipFunctionBody(Decl *D)
Determine whether we can skip parsing the body of a function definition, assuming we don't care about...
Definition: SemaDecl.cpp:15343
clang::QualType::PrimitiveCopyKind
PrimitiveCopyKind
Definition: Type.h:1235
clang::Decl::setLocalExternDecl
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition: DeclBase.h:1116
clang::Sema::ActOnNameClassifiedAsNonType
ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken)
Act on the result of classifying a name as a specific non-type declaration.
Definition: SemaDecl.cpp:1283
clang::Sema::PP
Preprocessor & PP
Definition: Sema.h:408
clang::EnumType
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:4849
clang::UnqualifiedIdKind::IK_ImplicitSelfParam
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
clang::DeclContext::isFunctionOrMethod
bool isFunctionOrMethod() const
Definition: DeclBase.h:1981
clang::Builtin::Context::isNoThrow
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:127
clang::CXXScopeSpec::getBeginLoc
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:74
clang::FunctionProtoType::getExtProtoInfo
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4245
clang::ASTContext::getObjCObjectPointerType
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
Definition: ASTContext.cpp:5642
clang::DeclSpec::getConstexprSpecLoc
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:781
clang::DeclarationNameInfo::getLoc
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
Definition: DeclarationName.h:796
clang::randstruct::randomizeStructureLayout
bool randomizeStructureLayout(const ASTContext &Context, RecordDecl *RD, llvm::SmallVectorImpl< Decl * > &FinalOrdering)
Definition: Randstruct.cpp:175
clang::EnumDecl::setPromotionType
void setPromotionType(QualType T)
Set the promotion type.
Definition: Decl.h:3873
clang::DeclarationNameInfo
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
Definition: DeclarationName.h:767
clang::Type::isIncompleteType
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2258
clang::DeclSpec::TST_auto
static const TST TST_auto
Definition: DeclSpec.h:299
clang::ASTContext::getConstantArrayType
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
Definition: ASTContext.cpp:3618
clang::Builtin::Context::isAuxBuiltinID
bool isAuxBuiltinID(unsigned ID) const
Return true if builtin ID belongs to AuxTarget.
Definition: Builtins.h:262
clang::ASTContext::DeclMustBeEmitted
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
Definition: ASTContext.cpp:11773
clang::NamedDecl::isReserved
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine if the declaration obeys the reserved identifier rules of the given language.
Definition: Decl.cpp:1110
clang::Sema::ActOnStartOfFunctionDef
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
Definition: SemaDecl.cpp:14897
clang::FunctionDecl::parameters
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2584
clang::FunctionDecl::setBody
void setBody(Stmt *B)
Definition: Decl.cpp:3130
CommentDiagnostic.h
clang::AttributedType::getModifiedType
QualType getModifiedType() const
Definition: Type.h:4900
clang::Sema::ActOnPopScope
void ActOnPopScope(SourceLocation Loc, Scope *S)
Scope actions.
Definition: SemaDecl.cpp:2212
clang::TST_union
@ TST_union
Definition: Specifiers.h:77
clang::Decl::getLocation
SourceLocation getLocation() const
Definition: DeclBase.h:432
ExitFunctionBodyRAII::ExitFunctionBodyRAII
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
Definition: SemaDecl.cpp:15379
clang::sema::CapturingScopeInfo::ReturnType
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:700
clang::FieldDecl::isAnonymousStructOrUnion
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4297
clang::CXXRecordDecl::getTemplateInstantiationPattern
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1886
clang::TSCS_unspecified
@ TSCS_unspecified
Definition: Specifiers.h:224
CheckMultiVersionFirstFunction
static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD)
Check the validity of a multiversion function declaration that is the first of its kind.
Definition: SemaDecl.cpp:11118
clang::LangAS::opencl_generic
@ opencl_generic
clang::Sema::ActOnNameClassifiedAsOverloadSet
ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet)
Act on the result of classifying a name as an overload set.
Definition: SemaDecl.cpp:1300
clang::Decl::addAttr
void addAttr(Attr *A)
Definition: DeclBase.cpp:903
NonTrivialTypeVisitor.h
clang::RISCV::Invalid
@ Invalid
Definition: RISCVVIntrinsicUtils.h:213
clang::DeclRefExpr
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1235
SDK_StructuredBinding
@ SDK_StructuredBinding
Definition: SemaDecl.cpp:8089
clang::NamespaceDecl
Represent a C++ namespace.
Definition: Decl.h:542
clang::ASTContext::mergeTypes
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
Definition: ASTContext.cpp:10490
clang::FunctionDecl
Represents a function declaration or definition.
Definition: Decl.h:1917
clang::Builtin::Context::isReturnsTwice
bool isReturnsTwice(unsigned ID) const
Return true if we know this builtin can return twice.
Definition: Builtins.h:137
clang::DeclaratorChunk::ParamInfo::Ident
IdentifierInfo * Ident
Definition: DeclSpec.h:1275
clang::RecordDecl
Represents a struct/union/class.
Definition: Decl.h:3996
clang::DeclContext::Equals
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2053
clang::DeclarationNameTable::getCXXConstructorName
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
Definition: DeclarationName.cpp:304
clang::TypeWithKeyword::getTagTypeKindName
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:5626
clang::CallExpr
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2813
clang::DeclSpec::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:526
clang::Sema::CheckRedeclarationModuleOwnership
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old)
We've determined that New is a redeclaration of Old.
Definition: SemaDecl.cpp:1638
clang::FunctionType::ExtInfo::getProducesResult
bool getProducesResult() const
Definition: Type.h:3842
clang::diag::kind
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:63
clang::LookupResult::FoundUnresolvedValue
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
clang::Sema::DelayedDiagnostics::add
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
Definition: DelayedDiagnostic.h:325
clang::FunctionDecl::getStorageClass
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2681
clang::CXXOperatorCallExpr
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
StmtCXX.h
clang::CXXConversionDecl::Create
static CXXConversionDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2821
clang::TypoCorrection::end
decl_iterator end()
Definition: TypoCorrection.h:236
clang::LangOptions::requiresStrictPrototypes
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
Definition: LangOptions.h:575
clang::FunctionDecl::setIsMultiVersion
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition: Decl.h:2525
clang::LookupResult::getLookupNameInfo
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:233
clang::DeclarationNameTable::getCXXLiteralOperatorName
DeclarationName getCXXLiteralOperatorName(IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
Definition: DeclarationName.cpp:368
clang::CXXConstructExpr
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1518
clang::Decl::setLocalOwningModule
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:795
clang::FunctionDecl::isDefined
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:3085
clang::Sema::RebuildTypeInCurrentInstantiation
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
Definition: SemaTemplate.cpp:11186
clang::OverloadCandidateSet::empty
bool empty() const
Definition: Overload.h:1130
clang::NamedDecl::declarationReplaces
bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer=true) const
Determine whether this declaration, if known to be well-formed within its context,...
Definition: Decl.cpp:1796
clang::ActionResult::isUsable
bool isUsable() const
Definition: Ownership.h:166
clang::ASTContext::GetBuiltinTypeError
GetBuiltinTypeError
Definition: ASTContext.h:2185
clang::StringLiteral::getString
StringRef getString() const
Definition: Expr.h:1862
clang::IdentifierInfo::isEditorPlaceholder
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
Definition: IdentifierTable.h:454
clang::ASTContext::getLangOpts
const LangOptions & getLangOpts() const
Definition: ASTContext.h:762
clang::UnqualifiedId::getKind
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1055
clang::TargetInfo::getIntWidth
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:477
clang::FunctionDecl::getInstantiatedFromMemberFunction
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:3781
clang::CharUnits::getQuantity
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
clang::CXXScopeSpec::isNotEmpty
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:193
clang::LookupResult::getRepresentativeDecl
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:550
clang::DeclSpec::SetTypeSpecType
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:832
clang::DeclSpec::getAtomicSpecLoc
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:571
clang::DeclaratorDecl::getTypeSourceInfo
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:796
clang::FixItHint::CreateReplacement
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
clang::ClassScopeFunctionSpecializationDecl::Create
static ClassScopeFunctionSpecializationDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, CXXMethodDecl *FD, bool HasExplicitTemplateArgs, const TemplateArgumentListInfo &TemplateArgs)
Definition: DeclTemplate.h:2653
clang::ICIS_NoInit
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:260
clang::ParenType
Sugar for parentheses used when specifying types.
Definition: Type.h:2750
clang::CXXConstructExpr::isElidable
bool isElidable() const
Whether this construction is elidable.
Definition: ExprCXX.h:1596
clang::Type::isIntegralOrEnumerationType
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:7307
clang::Sema::ActOnParamDeclarator
Decl * ActOnParamDeclarator(Scope *S, Declarator &D)
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
Definition: SemaDecl.cpp:14599
clang::DeclSpec
Captures information about "declaration specifiers".
Definition: DeclSpec.h:230
clang::CXXMethodDecl::isVirtual
bool isVirtual() const
Definition: DeclCXX.h:2039
clang::DeclSpec::getTypeSpecScope
CXXScopeSpec & getTypeSpecScope()
Definition: DeclSpec.h:522
clang::Declarator::isRedeclaration
bool isRedeclaration() const
Definition: DeclSpec.h:2672
clang::DeclSpec::SCS_extern
@ SCS_extern
Definition: DeclSpec.h:237
clang::Sema::AdjustDestructorExceptionSpec
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
Definition: SemaDeclCXX.cpp:13975
clang::DeclSpec::TSCS_thread_local
static const TSCS TSCS_thread_local
Definition: DeclSpec.h:250
clang::ReturnStmt
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:2804
ExitFunctionBodyRAII::~ExitFunctionBodyRAII
~ExitFunctionBodyRAII()
Definition: SemaDecl.cpp:15380
clang::DeclSpec::getRepAsType
ParsedType getRepAsType() const
Definition: DeclSpec.h:505
clang::Sema::deduceVarTypeFromInitializer
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:12555
clang::Decl::getMostRecentDecl
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:1041
clang::NestedNameSpecifierLocBuilder::getWithLocInContext
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: NestedNameSpecifier.cpp:692
clang::declaresSameEntity
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1240
clang::VarDecl::CallInit
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:923
clang::TypeSourceInfo::getTypeLoc
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:244
clang::UnqualifiedIdKind::IK_ConstructorTemplateId
@ IK_ConstructorTemplateId
A constructor named via a template-id.
clang::ValueDecl::setType
void setType(QualType newType)
Definition: Decl.h:715
ParsedTemplate.h
clang::ObjCInterfaceDecl::getDefinition
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition: DeclObjC.h:1530
clang::Builtin::Context::isPredefinedLibFunction
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition: Builtins.h:160
clang::CXXRecordDecl::setDescribedClassTemplate
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1857
clang::HLSLAnnotationAttr
Definition: Attr.h:192
clang::getAsTypeTemplateDecl
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
Definition: DeclTemplate.h:3432
ShouldDiagnoseUnusedDecl
static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D)
Definition: SemaDecl.cpp:1968
Initialization.h
clang::ASTContext::addTypedefNameForUnnamedTagDecl
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
Definition: ASTContext.cpp:12142
clang::FileScopeAsmDecl::Create
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, StringLiteral *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: Decl.cpp:5251
clang::CXXMethodDecl::getParent
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2110
clang::CXXMethodDecl
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1995
clang::CXXScopeSpec::isInvalid
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:196
clang::driver::types::getTypeName
const char * getTypeName(ID Id)
getTypeName - Return the name of the type for Id.
Definition: Types.cpp:52
clang::NamedDecl::setModulePrivate
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:661
clang::Type::isUndeducedType
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:7326
clang::Declarator::getMutableDeclSpec
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:1976
clang::ObjCIvarDecl::Package
@ Package
Definition: DeclObjC.h:1944
clang::Sema::ActOnFinishInlineFunctionDef
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:14926
clang::LookupResult::isAmbiguous
bool isAmbiguous() const
Definition: Lookup.h:301
clang::TypeSpecifierType
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:52
clang::ConstexprSpecKind::Unspecified
@ Unspecified
clang::Decl::getDeclContext
DeclContext * getDeclContext()
Definition: DeclBase.h:441
clang::FunctionDecl::isOutOfLine
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition: Decl.cpp:4115
clang::SourceManager::getSpellingLoc
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
Definition: SourceManager.h:1216
clang::VarDecl::DefinitionKind
DefinitionKind
Definition: Decl.h:1252
clang::StorageClass
StorageClass
Storage classes.
Definition: Specifiers.h:236
clang::NamedDecl::getName
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:274
clang::DeclSpec::getThreadStorageClassSpec
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:460
clang::LocalInstantiationScope::InstantiatedLocal
void InstantiatedLocal(const Decl *D, Decl *Inst)
Definition: SemaTemplateInstantiate.cpp:4068